mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
feat(desktop): signed-in browser pane with extensions, previews, prompts and agent safeguards (#63002)
This commit is contained in:
parent
4288e1dd69
commit
cd0d037d68
443 changed files with 38424 additions and 3254 deletions
2
.github/release/entitlements/desktop.plist
vendored
2
.github/release/entitlements/desktop.plist
vendored
|
|
@ -6,5 +6,7 @@
|
|||
<true/>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.camera</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
|
|
|||
10
bun.lock
10
bun.lock
|
|
@ -348,6 +348,7 @@
|
|||
"electron-context-menu": "5.0.0",
|
||||
"electron-log": "^5",
|
||||
"electron-updater": "6.8.9",
|
||||
"ffi-rs": "1.3.7",
|
||||
"lighthouse": "13.4.1",
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
@ -412,10 +413,12 @@
|
|||
"@tanstack/solid-query": "5.91.4",
|
||||
"@tanstack/solid-virtual": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"ffi-rs": "1.3.7",
|
||||
"fuzzysort": "catalog:",
|
||||
"ghostty-web": "github:anomalyco/ghostty-web#e91e38a9ceb13c566ddfa15185a9393849f712a9",
|
||||
"knobs": "npm:@kitlangton/knobs@0.4.0-next.22",
|
||||
"solid-js": "catalog:",
|
||||
"tldts": "7.5.1",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@happy-dom/global-registrator": "20.0.11",
|
||||
|
|
@ -568,6 +571,7 @@
|
|||
"dependencies": {
|
||||
"@opencode/plugin": "workspace:*",
|
||||
"@opencode/schema": "workspace:*",
|
||||
"@opencode/util": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
@ -4216,7 +4220,9 @@
|
|||
|
||||
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
|
||||
|
||||
"tldts-core": ["tldts-core@7.4.11", "", {}, "sha512-CW3WN2rIIE/Of21mulhgnGOwoDyEFNygyIBOONSdyAuSATgMMUCpLeUlB+E8sAwA5xRV9hYPl+kyZ9citHCaKg=="],
|
||||
"tldts": ["tldts@7.5.1", "", { "dependencies": { "tldts-core": "^7.5.1" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-UW1Z5afSpu5qA0qhDnaynyiwPa+/VC7J/mofz72R032It5DUTUWk8I502cAitA6qMQV1x7IwNHg7pCBNVORVww=="],
|
||||
|
||||
"tldts-core": ["tldts-core@7.5.1", "", {}, "sha512-GGSowIH9Pp52ym/x0OxBBNqS2DuqlLL91YNnlnj+k+ZWjJQ+ilNxpwP7/RT+iX1gzuafhj1l7j46CNVqm+xAeQ=="],
|
||||
|
||||
"tldts-icann": ["tldts-icann@7.4.11", "", { "dependencies": { "tldts-core": "^7.4.11" } }, "sha512-1p+NDJ7FUYCliESmsQl9EW5Um8JIyFheiy6Y6ZoHho27d+TLAGFa0gMf1VOVy02vNY1aQo6xeKiaGj45+7P+PA=="],
|
||||
|
||||
|
|
@ -4852,6 +4858,8 @@
|
|||
|
||||
"tiny-async-pool/semver": ["semver@5.7.2", "", { "bin": { "semver": "bin/semver" } }, "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g=="],
|
||||
|
||||
"tldts-icann/tldts-core": ["tldts-core@7.4.11", "", {}, "sha512-CW3WN2rIIE/Of21mulhgnGOwoDyEFNygyIBOONSdyAuSATgMMUCpLeUlB+E8sAwA5xRV9hYPl+kyZ9citHCaKg=="],
|
||||
|
||||
"type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
|
||||
|
||||
"unused-filename/escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
|
||||
|
|
|
|||
|
|
@ -93,6 +93,14 @@ This section is the single source for loading indicators across `app`, `ui`, `se
|
|||
- Every other loading state uses `Loader` (`@opencode/ui/loader`): page, pane and file loads, browser reload, search, connecting, authenticating, sending, installing. Use a purpose-built indicator only when the state has one, such as the titlebar update ring.
|
||||
- Choose the indicator at each call site. Never restyle a shared indicator (`Loader`, `ActivityRing`, `Spinner`) to look like another one; that silently changes every caller.
|
||||
|
||||
## Floating surfaces over native pages
|
||||
|
||||
A native page view, such as the browser pane's, paints above every DOM element, so `src/runtime/plugin/embeds.tsx` hides it while floating app UI overlaps it.
|
||||
|
||||
- Mark the painted box of a floating surface with `data-floating-overlay` for its whole visible lifetime, including its exit animation. Mark the surface, not a full-window transparent portal wrapper.
|
||||
- Popper positioners, `aria-modal` dialogs, open `<dialog>` elements and open popovers count without the marker. Tooltips never cover the page.
|
||||
- A positioned surface that takes pointer input and is portalled to `document.body` after the app root also counts without the marker. It is a fallback: mark new surfaces.
|
||||
|
||||
## Scrolling
|
||||
|
||||
This section is the single source for scroll containers across `app`, `ui`, `session-ui`, `gui-plugins` and `desktop`.
|
||||
|
|
|
|||
|
|
@ -214,6 +214,18 @@ story.beforeEach(async ({ mount, page }) => {
|
|||
}, modules)
|
||||
})
|
||||
|
||||
story("routes an exact HTML file to the pane and reports an unavailable pane instead of opening a file preview", async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
await expect(root.getByText("Registrations: 1", { exact: true })).toBeVisible()
|
||||
const open = root.getByRole("button", { name: "Open workspace HTML" })
|
||||
await open.click()
|
||||
await expect(root.getByText("file:///repo/report.html", { exact: true })).toBeVisible()
|
||||
await root.getByRole("button", { name: "Pane away" }).click()
|
||||
await open.click()
|
||||
await expect(root.getByText(/Can't open this workspace file in the browser pane/)).toBeVisible()
|
||||
await expect(root.getByRole("tab", { name: "report.html" })).toHaveCount(0)
|
||||
})
|
||||
|
||||
story("closes a blank browser tab from its address field without closing the session", async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
const outside = root.getByRole("button", { name: "Beta", exact: true })
|
||||
|
|
@ -249,31 +261,31 @@ story("toggles the element picker from the shortcut only inside the browser pane
|
|||
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
|
||||
|
||||
await root.getByRole("button", { name: "Blank page", exact: true }).click()
|
||||
const inspect = root.getByRole("button", { name: "Select an element to comment on", exact: true })
|
||||
// The comment tool has no button in the bar; while it waits for a pick, the pane says so in a status line.
|
||||
const picking = root.getByText("Click part of the page to comment on it. Press Escape to cancel.", { exact: true })
|
||||
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
|
||||
await expect(inspect).toBeDisabled()
|
||||
await address.click()
|
||||
await address.press("ControlOrMeta+Shift+c")
|
||||
await expect(root.getByTestId("browser-inspects")).toHaveText("[]")
|
||||
|
||||
await root.getByRole("button", { name: "First inventory", exact: true }).click()
|
||||
await expect(inspect).toBeEnabled()
|
||||
await expect(address).not.toHaveValue("")
|
||||
|
||||
await outside.focus()
|
||||
await outside.press("ControlOrMeta+Shift+c")
|
||||
await expect(inspect).toHaveAttribute("aria-pressed", "false")
|
||||
await expect(picking).toHaveCount(0)
|
||||
await expect(root.getByTestId("browser-inspects")).toHaveText("[]")
|
||||
|
||||
await address.click()
|
||||
await expect(address).toBeFocused()
|
||||
await address.press("ControlOrMeta+Shift+c")
|
||||
await expect(inspect).toHaveAttribute("aria-pressed", "true")
|
||||
await expect(picking).toBeAttached()
|
||||
await expect(root.getByTestId("browser-inspects")).toHaveText(
|
||||
'[{"tabID":"tab_33333333-3333-3333-3333-333333333333","enabled":true}]',
|
||||
)
|
||||
|
||||
await address.press("ControlOrMeta+Shift+c")
|
||||
await expect(inspect).toHaveAttribute("aria-pressed", "false")
|
||||
await expect(picking).toHaveCount(0)
|
||||
await expect(root.getByTestId("browser-inspects")).toHaveText(
|
||||
'[{"tabID":"tab_33333333-3333-3333-3333-333333333333","enabled":true},{"tabID":"tab_33333333-3333-3333-3333-333333333333","enabled":false}]',
|
||||
)
|
||||
|
|
@ -325,6 +337,23 @@ story("keeps in-page shortcuts in the editor and forwards toolbar, review and cl
|
|||
await expect(root.getByTestId("session-state")).toHaveText("open")
|
||||
})
|
||||
|
||||
story("the pane's toolbar shortcut works from inside the options menu's More tools", async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
const mod = (await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform))) ? "Meta" : "Control"
|
||||
const toggle = root.getByRole("button", { name: "Toggle browser toolbar", exact: true })
|
||||
await root.getByRole("button", { name: "Beta", exact: true }).click()
|
||||
await root.getByRole("button", { name: "First inventory", exact: true }).click()
|
||||
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false")
|
||||
|
||||
// The submenu is a portal of its own, outside the pane: it must still count as the pane for the pane's shortcuts.
|
||||
await root.getByRole("button", { name: "Browser options", exact: true }).click()
|
||||
await page.getByRole("menuitem", { name: "More tools", exact: true }).press("ArrowRight")
|
||||
await expect(page.getByRole("menu", { name: "More tools", exact: true }).getByRole("menuitem").first()).toBeFocused()
|
||||
await page.keyboard.press(`${mod}+Shift+m`)
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "true")
|
||||
})
|
||||
|
||||
story(
|
||||
"reopening the side panel focuses a blank tab's address and closing it returns to the composer",
|
||||
async ({ page }) => {
|
||||
|
|
@ -680,6 +709,65 @@ story("keeps a restored browser tab selected and undrawn until the desktop's fir
|
|||
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
})
|
||||
|
||||
// An agent's tabs.open or tabs.focus shows its tab: it comes to the front over the file the person had selected.
|
||||
story("an agent show request selects its tab over the selected file, and a plugin open wakes the suspended binding", async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
await root.getByRole("button", { name: "Beta", exact: true }).click()
|
||||
await root.getByRole("button", { name: "First inventory", exact: true }).click()
|
||||
const file = root.getByRole("tab", { name: "beta.ts" })
|
||||
await file.click()
|
||||
await root.getByRole("button", { name: "Agent show request" }).click()
|
||||
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(file).toHaveAttribute("aria-selected", "false")
|
||||
await root.getByRole("button", { name: "Suspend binding" }).click()
|
||||
await root.getByRole("button", { name: "Plugin open and close" }).click()
|
||||
await expect(root.getByText("Plugin closed: true", { exact: true })).toBeVisible()
|
||||
await expect(root.getByText("Registrations: 3", { exact: true })).toBeVisible()
|
||||
})
|
||||
|
||||
story("an agent show request opens the closed pane and leaves the keyboard in the composer", async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
const mac = await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform))
|
||||
const composer = root.getByRole("textbox", { name: "Composer", exact: true })
|
||||
const side = root.getByTestId("side-state")
|
||||
await root.getByRole("button", { name: "Beta", exact: true }).click()
|
||||
await root.getByRole("button", { name: "First inventory", exact: true }).click()
|
||||
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
await composer.focus()
|
||||
await page.keyboard.press(mac ? "Meta+Shift+r" : "Control+Shift+r")
|
||||
await expect(side).toHaveText("closed")
|
||||
// The agent's request arrives with no input from the person, so nothing but the reveal could move the keyboard.
|
||||
await root.getByRole("button", { name: "Agent show request" }).dispatchEvent("click")
|
||||
await expect(side).toHaveText("open")
|
||||
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(composer).toBeFocused()
|
||||
})
|
||||
|
||||
story("?W right after an agent shows another page closes that browser tab, not the session", async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
await root.getByRole("button", { name: "Beta", exact: true }).click()
|
||||
await root.getByRole("button", { name: "First inventory", exact: true }).click()
|
||||
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
|
||||
await address.click()
|
||||
// The request arrives with no input from the person: the keyboard stays in the pane, where ?W is the pane's.
|
||||
await root.getByRole("button", { name: "Agent shows another page", exact: true }).dispatchEvent("click")
|
||||
await expect(root.getByRole("tab", { selected: true })).toHaveCount(1)
|
||||
await expect(root.getByTestId("selected")).toHaveText("browser:tab_55555555-5555-5555-5555-555555555555")
|
||||
await expect(address).toBeFocused()
|
||||
await page.keyboard.press("ControlOrMeta+w")
|
||||
await expect(root.getByTestId("browser-closes")).toHaveText('["tab_55555555-5555-5555-5555-555555555555"]')
|
||||
await expect(root.getByTestId("session-state")).toHaveText("open")
|
||||
})
|
||||
|
||||
story("a browser tab behind a file tab says that its page waits for the person", async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
await root.getByRole("button", { name: "Beta", exact: true }).click()
|
||||
await root.getByRole("button", { name: "First inventory", exact: true }).click()
|
||||
await root.getByRole("tab", { name: "beta.ts" }).click()
|
||||
await root.getByRole("button", { name: "Page prompt" }).click()
|
||||
await expect(root.getByRole("img", { name: "Waiting for you" })).toBeVisible()
|
||||
})
|
||||
|
||||
story(
|
||||
"keeps the browser tabs while the pane's Ipc is away and registers them again when it returns",
|
||||
async ({ page }) => {
|
||||
|
|
@ -703,3 +791,82 @@ story(
|
|||
await expect(tabs).toHaveText(["beta.ts", "Preview"])
|
||||
},
|
||||
)
|
||||
|
||||
story(
|
||||
"runs no shortcut from a page prompt, even after a click on its dimmed page; the permission bar and a drawer keep theirs",
|
||||
async ({ page }) => {
|
||||
const root = page.getByTestId("browser-region-fixture")
|
||||
const reloads = root.getByTestId("browser-reloads")
|
||||
const reviews = root.getByTestId("review-toggles")
|
||||
await expect(root.getByText("Registrations: 1", { exact: true })).toBeVisible()
|
||||
await root.getByRole("button", { name: "Beta", exact: true }).click()
|
||||
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
|
||||
await root.getByRole("button", { name: "First inventory", exact: true }).click()
|
||||
|
||||
await root.getByRole("button", { name: "Page prompt", exact: true }).click()
|
||||
const dialog = root.getByRole("alertdialog", { name: "beta.example says" })
|
||||
const field = dialog.getByRole("textbox", { name: "Your answer" })
|
||||
const dimmed = root.locator("[data-browser-prompt]")
|
||||
await expect(field).toBeFocused()
|
||||
// Neither the pane's reload nor the session's review toggle runs from the prompt.
|
||||
await field.press("ControlOrMeta+r")
|
||||
await field.press("ControlOrMeta+Shift+r")
|
||||
// A click on the dimmed page keeps the keyboard in the prompt rather than giving it to the pane behind.
|
||||
await dimmed.click({ position: { x: 4, y: 4 } })
|
||||
await expect(field).toBeFocused()
|
||||
await page.keyboard.press("ControlOrMeta+r")
|
||||
await expect(reloads).toHaveText("0")
|
||||
await expect(reviews).toHaveText("0")
|
||||
|
||||
// F6, Shift+F6 and the address shortcut leave the prompt open for the address field, as in Chrome; Tab comes back.
|
||||
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
|
||||
|
||||
for (const chord of ["F6", "Shift+F6", "ControlOrMeta+l"]) {
|
||||
await field.focus()
|
||||
await page.keyboard.press(chord)
|
||||
await expect(address).toBeFocused()
|
||||
await expect(dialog).toBeVisible()
|
||||
}
|
||||
|
||||
await expect(async () => {
|
||||
await page.keyboard.press("Tab")
|
||||
await expect(field).toBeFocused({ timeout: 100 })
|
||||
}).toPass()
|
||||
|
||||
// The prompt is modal for its tab only: on the address field the pane's shortcuts work and the prompt stays open.
|
||||
await address.click()
|
||||
await address.press("ControlOrMeta+r")
|
||||
await expect(reloads).toHaveText("1")
|
||||
await expect(dialog).toBeVisible()
|
||||
// A click on the dimmed page brings the keyboard back, where Escape is the prompt's cancel.
|
||||
await dimmed.click({ position: { x: 4, y: 4 } })
|
||||
await expect(field).toBeFocused()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(dialog).toBeHidden()
|
||||
|
||||
// The permission bar is not modal: the pane's shortcuts work there, and Escape is its "not now".
|
||||
await root.getByRole("button", { name: "Permission request", exact: true }).click()
|
||||
const bar = root.locator('[data-component="browser-prompt"]')
|
||||
const never = bar.getByRole("button", { name: "Never allow", exact: true })
|
||||
await expect(never).toBeFocused()
|
||||
await never.press("ControlOrMeta+r")
|
||||
await expect(reloads).toHaveText("2")
|
||||
await never.press("Escape")
|
||||
await expect(bar).toBeHidden()
|
||||
|
||||
// Another modal surface, as a mobile drawer, keeps the app's shortcuts; markup alone, as a chat message's, cannot
|
||||
// claim the keyboard.
|
||||
await page.evaluate(() => {
|
||||
const drawer = document.createElement("div")
|
||||
drawer.setAttribute("role", "dialog")
|
||||
drawer.setAttribute("aria-modal", "true")
|
||||
drawer.setAttribute("data-owns-keyboard", "")
|
||||
drawer.append(Object.assign(document.createElement("button"), { textContent: "Drawer action" }))
|
||||
document.body.append(drawer)
|
||||
})
|
||||
const action = page.getByRole("button", { name: "Drawer action", exact: true })
|
||||
await action.focus()
|
||||
await action.press("ControlOrMeta+Shift+r")
|
||||
await expect(reviews).toHaveText("1")
|
||||
},
|
||||
)
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
168
packages/app/component-tests/browser-settings.spec.ts
Normal file
168
packages/app/component-tests/browser-settings.spec.ts
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import { expect, sourceURL, story } from "../../stories/playwright/story"
|
||||
|
||||
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
|
||||
|
||||
const modules = {
|
||||
fixture: source("../../gui-plugins/src/browser/settings.fixture.tsx"),
|
||||
ui: source("../src/runtime/plugin/ui.tsx"),
|
||||
}
|
||||
|
||||
// Any story loads the app styles; the fixture mounts the real Settings > Browser page beside it. `target` is the entry
|
||||
// a settings search or the command palette is revealing.
|
||||
async function open(page: Page, options?: { target?: string; extensions?: boolean; installed?: boolean }) {
|
||||
await page.evaluate(
|
||||
async (input) => {
|
||||
const [{ mountBrowserSettings }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
|
||||
|
||||
mountBrowserSettings({
|
||||
ui,
|
||||
target: input.options?.target,
|
||||
extensions: input.options?.extensions,
|
||||
installed: input.options?.installed,
|
||||
})
|
||||
},
|
||||
{ modules, options },
|
||||
)
|
||||
|
||||
const root = page.getByTestId("browser-settings-fixture")
|
||||
|
||||
return {
|
||||
root,
|
||||
advanced: root.getByRole("button", { name: /^Advanced/ }),
|
||||
stored: root.getByTestId("browser-settings-stored"),
|
||||
}
|
||||
}
|
||||
|
||||
story.beforeEach(async ({ mount }) => {
|
||||
await mount("ui-line-comment--editor")
|
||||
})
|
||||
|
||||
story("a search that lands inside Advanced opens it once, and the person's toggle wins after that", async ({ page }) => {
|
||||
const view = await open(page, { target: "settings-browser-sites" })
|
||||
|
||||
// Open for the visit, without the device remembering it.
|
||||
await expect(view.advanced).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(view.stored).not.toContainText("advanced")
|
||||
|
||||
// The search's target stays set for the whole visit: closing must still close.
|
||||
await view.advanced.click()
|
||||
await expect(view.advanced).toHaveAttribute("aria-expanded", "false")
|
||||
await expect(view.stored).toContainText('"advanced":false')
|
||||
|
||||
await view.advanced.click()
|
||||
await expect(view.advanced).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(view.stored).toContainText('"advanced":true')
|
||||
await view.advanced.click()
|
||||
await expect(view.advanced).toHaveAttribute("aria-expanded", "false")
|
||||
})
|
||||
|
||||
story("Add an extension aligns controls without top clipping and switches cleanly into a confirmation step", async ({ page }) => {
|
||||
const view = await open(page, { extensions: true })
|
||||
|
||||
await view.root.getByRole("button", { name: "Add extension" }).click()
|
||||
const dialog = page.getByRole("dialog", { name: "Add an extension" })
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(dialog.getByText("LastPass: Free Password Manager")).toBeVisible()
|
||||
await page.evaluate(() => document.fonts.ready.then(() => undefined))
|
||||
|
||||
// Top URL input and Add button sit inside the scrollable dialog body with clearance for borders and focus rings.
|
||||
const metrics = await dialog.evaluate((node) => {
|
||||
const body = node.querySelector('[data-slot="dialog-body"]')?.getBoundingClientRect()
|
||||
const title = node.querySelector('[data-slot="dialog-title"]')?.getBoundingClientRect()
|
||||
const closeSvg = node.querySelector('[data-slot="dialog-close-button"] svg')?.getBoundingClientRect()
|
||||
const input = node.querySelector('[data-component="text-input-v2"]')?.getBoundingClientRect()
|
||||
const topAdd = node.querySelector('[data-component="text-input-v2"]')?.parentElement?.querySelector("button")?.getBoundingClientRect()
|
||||
const browserHeading = Array.from(node.querySelectorAll("span")).find((el) => el.textContent === "From your browsers")?.getBoundingClientRect()
|
||||
const selectChevron = node.querySelector('[data-slot="select-v2-chevron"]')?.getBoundingClientRect()
|
||||
const devSummary = node.querySelector("details > summary")?.getBoundingClientRect()
|
||||
const done = node.querySelector('[data-slot="dialog-footer"] button')?.getBoundingClientRect()
|
||||
const rowButtons = Array.from(node.querySelectorAll('[data-slot="menu-scroll-content"] button')).map((el) => el.getBoundingClientRect())
|
||||
|
||||
return {
|
||||
topClearanceInput: body && input ? Math.round(input.top - body.top) : -1,
|
||||
topClearanceButton: body && topAdd ? Math.round(topAdd.top - body.top) : -1,
|
||||
leftDeltas:
|
||||
title && input && browserHeading && devSummary
|
||||
? [input.left - title.left, browserHeading.left - title.left, devSummary.left - title.left].map((value) => Math.round(value))
|
||||
: [],
|
||||
rightDeltas:
|
||||
done && closeSvg && topAdd && selectChevron
|
||||
? [
|
||||
closeSvg.right - done.right,
|
||||
topAdd.right - done.right,
|
||||
selectChevron.right - done.right,
|
||||
...rowButtons.map((box) => box.right - done.right),
|
||||
].map((value) => Math.round(value))
|
||||
: [],
|
||||
}
|
||||
})
|
||||
|
||||
expect(metrics.topClearanceInput).toBeGreaterThanOrEqual(4)
|
||||
expect(metrics.topClearanceButton).toBeGreaterThanOrEqual(4)
|
||||
expect(metrics.leftDeltas).toEqual([0, 0, 0])
|
||||
expect(metrics.rightDeltas.every((delta) => delta === 0)).toBe(true)
|
||||
|
||||
// Clicking Add switches the whole dialog into a concise confirmation step without the browser list underneath.
|
||||
await dialog.getByRole("button", { name: "Add", exact: true }).nth(1).click()
|
||||
const confirm = page.getByRole("dialog", { name: 'Add "LastPass: Free Password Manager"?' })
|
||||
await expect(confirm).toBeVisible()
|
||||
await expect(confirm.getByText("It can:")).toBeVisible()
|
||||
await expect(confirm.getByText("Read and change every page you visit")).toBeVisible()
|
||||
await expect(confirm.getByText("See and change your sign-ins")).toBeVisible()
|
||||
await expect(confirm.getByText("May not fully work here")).toBeVisible()
|
||||
await expect(confirm.getByText("From your browsers")).toHaveCount(0)
|
||||
await expect(confirm.getByText("Details")).toHaveCount(0)
|
||||
await expect(confirm.getByText(/Copied from another browser/)).toHaveCount(0)
|
||||
|
||||
// Cancel returns smoothly to the picker list.
|
||||
await confirm.getByRole("button", { name: "Cancel" }).click()
|
||||
await expect(page.getByRole("dialog", { name: "Add an extension" })).toBeVisible()
|
||||
await expect(dialog.getByText("From your browsers")).toBeVisible()
|
||||
|
||||
// Unsupported extensions offer "Add anyway" in the confirmation footer.
|
||||
await dialog.getByRole("button", { name: "Add anyway" }).click()
|
||||
const unsupported = page.getByRole("dialog", { name: 'Add "OpenCode Browse"?' })
|
||||
await expect(unsupported).toBeVisible()
|
||||
await expect(unsupported.getByText("Probably won't work here")).toBeVisible()
|
||||
await expect(unsupported.getByRole("button", { name: "Add anyway" })).toBeVisible()
|
||||
await unsupported.getByRole("button", { name: "Cancel" }).click()
|
||||
|
||||
// Approving installs the extension and returns to the picker with status and updated row state.
|
||||
await dialog.getByRole("button", { name: "Add", exact: true }).nth(1).click()
|
||||
await confirm.getByRole("button", { name: "Add extension" }).click()
|
||||
await expect(page.getByRole("dialog", { name: "Add an extension" })).toBeVisible()
|
||||
await expect(dialog.getByRole("status")).toContainText("Added LastPass: Free Password Manager.")
|
||||
await expect(dialog.getByRole("button", { name: "Added" })).toBeDisabled()
|
||||
})
|
||||
|
||||
story("installed extension rows stack compatibility under the name and align controls cleanly", async ({ page }) => {
|
||||
const view = await open(page, { extensions: true, installed: true })
|
||||
const section = view.root.locator('section.settings-section[aria-label="Extensions"]')
|
||||
|
||||
await expect(section.getByText("May not fully work here")).toBeVisible()
|
||||
await expect(section.getByText("Probably won't work here")).toBeVisible()
|
||||
|
||||
const metrics = await section.evaluate((node) => {
|
||||
const rows = Array.from(node.querySelectorAll('[data-component="settings-row"]')).slice(0, 3)
|
||||
|
||||
return rows.map((row) => {
|
||||
const compatInControl = row.querySelector('[data-slot="settings-row-control"] [data-compatibility]') !== null
|
||||
const compatInCopy = row.querySelector('[data-slot="settings-row-copy"] [data-compatibility]') !== null
|
||||
const trash = row.querySelector('[data-slot="settings-row-control"] button')?.getBoundingClientRect()
|
||||
const toggle = row.querySelector('[data-slot="settings-row-control"] [data-component="switch"]')?.getBoundingClientRect()
|
||||
|
||||
return {
|
||||
compatInControl,
|
||||
compatInCopy,
|
||||
trashLeft: trash ? Math.round(trash.left) : -1,
|
||||
toggleRight: toggle ? Math.round(toggle.right) : -1,
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
expect(metrics.every((row) => !row.compatInControl)).toBe(true)
|
||||
expect(metrics.map((row) => row.compatInCopy)).toEqual([true, true, false])
|
||||
expect(new Set(metrics.map((row) => row.trashLeft)).size).toBe(1)
|
||||
expect(new Set(metrics.map((row) => row.toggleRight)).size).toBe(1)
|
||||
})
|
||||
410
packages/app/component-tests/browser-site-chooser.spec.ts
Normal file
410
packages/app/component-tests/browser-site-chooser.spec.ts
Normal file
|
|
@ -0,0 +1,410 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
import { expect, sourceURL, story } from "../../stories/playwright/story"
|
||||
|
||||
// What the fixture's faked browser profile answers; see `SiteScenario` in the fixture.
|
||||
type SiteScenario = {
|
||||
sites: number | "locked"
|
||||
hold?: boolean
|
||||
partial?: boolean
|
||||
skipped?: number
|
||||
protected?: number
|
||||
empty?: boolean
|
||||
site?: { name: string; choose: boolean }
|
||||
reveal?: boolean
|
||||
}
|
||||
|
||||
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
|
||||
|
||||
const modules = {
|
||||
fixture: source("../../gui-plugins/src/browser/site-chooser.fixture.tsx"),
|
||||
ui: source("../src/runtime/plugin/ui.tsx"),
|
||||
}
|
||||
|
||||
// Any story loads the app styles; the fixture opens the real import dialog in the real dialog host beside it. Most
|
||||
// cases here are about the site list, so the dialog opens with it shown unless the case says otherwise.
|
||||
async function open(page: Page, given: SiteScenario, direction: "ltr" | "rtl" = "ltr") {
|
||||
const scenario = { reveal: true, ...given }
|
||||
|
||||
await page.evaluate(
|
||||
async (input) => {
|
||||
const [{ mountSiteChooser }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
|
||||
|
||||
mountSiteChooser({ ui, scenario: input.scenario, direction: input.direction })
|
||||
},
|
||||
{ modules, scenario, direction },
|
||||
)
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: /^Import from Google Chrome/ })
|
||||
|
||||
return {
|
||||
dialog,
|
||||
list: dialog.getByRole("listbox", { name: "Sites" }),
|
||||
options: dialog.getByRole("option"),
|
||||
search: dialog.getByRole("searchbox", { name: "Search sites" }),
|
||||
// "Import all" until the person changes the choice, then how many sites it brings.
|
||||
importButton: dialog.getByRole("button", { name: /^Import (all|[\d,]+ sites?)$/ }),
|
||||
selectNone: dialog.getByRole("button", { name: "Select none", exact: true }),
|
||||
// The dialog is modal, so the record beside it is hidden from the accessibility tree.
|
||||
record: page.getByTestId("site-chooser-imports"),
|
||||
}
|
||||
}
|
||||
|
||||
story.beforeEach(async ({ mount }) => {
|
||||
await mount("ui-line-comment--editor")
|
||||
})
|
||||
|
||||
story("lists 5,000 sites in a window of rows, as one keyboard stop with roving focus", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5_000 })
|
||||
|
||||
await expect(view.options.first()).toHaveAttribute("data-site", "github.com")
|
||||
await expect(view.list).toHaveAttribute("aria-multiselectable", "true")
|
||||
await expect(view.options.first()).toHaveAttribute("aria-setsize", "5000")
|
||||
// Every site comes over until the person changes that.
|
||||
await expect(view.dialog.getByText("5,000 of 5,000 selected")).toBeVisible()
|
||||
await expect(
|
||||
view.dialog.getByText("Copies cookies for all 5,000 sites. The other browser keeps its own."),
|
||||
).toBeVisible()
|
||||
expect(await view.options.count()).toBeLessThan(45)
|
||||
await expect(view.importButton).toHaveText("Import all")
|
||||
|
||||
// Tab goes from the search, past the profile and the selection's one enabled action, to the list, then out of it.
|
||||
await expect(view.search).toBeFocused()
|
||||
await page.keyboard.press("Tab")
|
||||
await expect(view.dialog.getByRole("button", { name: /Browser profile/ })).toBeFocused()
|
||||
await page.keyboard.press("Tab")
|
||||
await expect(view.selectNone).toBeFocused()
|
||||
await page.keyboard.press("Tab")
|
||||
await expect(view.list).toBeFocused()
|
||||
await page.keyboard.press("Tab")
|
||||
await expect(view.dialog.getByRole("button", { name: "Choose sites" })).toBeFocused()
|
||||
await page.keyboard.press("Shift+Tab")
|
||||
await expect(view.list).toBeFocused()
|
||||
await view.selectNone.click()
|
||||
await expect(view.dialog.getByText("0 of 5,000 selected")).toBeVisible()
|
||||
await expect(view.importButton).toBeDisabled()
|
||||
await view.list.focus()
|
||||
|
||||
// Down moves, Space toggles, End goes to the last site, and type-ahead jumps to the next site that starts so.
|
||||
await page.keyboard.press("ArrowDown")
|
||||
await page.keyboard.press("Space")
|
||||
await expect(view.dialog.getByRole("option", { name: /linear\.app/ })).toHaveAttribute("aria-selected", "true")
|
||||
await page.keyboard.press("End")
|
||||
await expect(view.list).toHaveAttribute("aria-activedescendant", /site-4999\.example\.co\.uk$/)
|
||||
await expect(view.dialog.locator('[data-site="site-4999.example.co.uk"]')).toBeVisible()
|
||||
expect(await view.options.count()).toBeLessThan(45)
|
||||
await page.keyboard.press("Home")
|
||||
await page.keyboard.type("fig")
|
||||
await expect(view.list).toHaveAttribute("aria-activedescendant", /figma\.com$/)
|
||||
await page.keyboard.press("Space")
|
||||
await expect(view.dialog.getByText("2 of 5,000 selected")).toBeVisible()
|
||||
await expect(view.importButton).toHaveText("Import 2 sites")
|
||||
|
||||
// Enter imports what is selected; a clean import closes the dialog.
|
||||
await page.keyboard.press("Enter")
|
||||
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", sites: ["linear.app", "figma.com"] })])
|
||||
await expect(view.record).toHaveAttribute("data-closed", "true")
|
||||
await expect(view.record).toHaveAttribute("data-imported", "1")
|
||||
})
|
||||
|
||||
story("says what Select acts on while a search is active, and only offers what would change something", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5_000 })
|
||||
|
||||
await view.selectNone.click()
|
||||
await view.search.fill("site-01")
|
||||
await expect(view.dialog.getByText("100 shown, 0 selected")).toBeVisible()
|
||||
await view.dialog.getByRole("button", { name: "Select 100 shown", exact: true }).click()
|
||||
await expect(view.dialog.getByRole("button", { name: "Deselect 100 shown", exact: true })).toBeEnabled()
|
||||
await expect(view.dialog.getByRole("button", { name: "Select 100 shown", exact: true })).toBeDisabled()
|
||||
await view.search.fill("github")
|
||||
await expect(view.options).toHaveCount(1)
|
||||
await view.options.click()
|
||||
await expect(view.dialog.getByText("1 shown, 101 selected")).toBeVisible()
|
||||
|
||||
// In the search, Escape clears it first, and closes the dialog only once it is empty.
|
||||
await view.search.focus()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(view.search).toHaveValue("")
|
||||
await expect(view.dialog).toBeVisible()
|
||||
await expect(view.dialog.getByText("101 of 5,000 selected")).toBeVisible()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(view.record).toHaveAttribute("data-closed", "true")
|
||||
})
|
||||
|
||||
story("leaves Escape and ArrowDown to an input method while it composes", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5 })
|
||||
const composing = { key: "Escape", keyCode: 229, isComposing: true }
|
||||
|
||||
// An empty search: Escape ends the composition, not the dialog.
|
||||
await view.search.dispatchEvent("compositionstart")
|
||||
await view.search.dispatchEvent("keydown", composing)
|
||||
await view.search.dispatchEvent("keydown", { ...composing, key: "ArrowDown" })
|
||||
await expect(view.dialog).toBeVisible()
|
||||
await expect(view.search).toBeFocused()
|
||||
await view.search.dispatchEvent("compositionend")
|
||||
|
||||
await view.search.fill("git")
|
||||
await view.search.dispatchEvent("compositionstart")
|
||||
await view.search.dispatchEvent("keydown", composing)
|
||||
await expect(view.search).toHaveValue("git")
|
||||
await view.search.dispatchEvent("compositionend")
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(view.search).toHaveValue("")
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(view.record).toHaveAttribute("data-closed", "true")
|
||||
})
|
||||
|
||||
story("switches profiles back to every site chosen, at the top, and reads a profile only once while open", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5_000 })
|
||||
|
||||
await view.options.first().click()
|
||||
await view.list.focus()
|
||||
await page.keyboard.press("End")
|
||||
await view.dialog.getByRole("button", { name: /Browser profile/ }).click()
|
||||
await page.getByRole("option", { name: "Google Chrome · Home" }).click()
|
||||
await expect(view.options).toHaveCount(4)
|
||||
await expect(view.dialog.getByText("4 of 4 selected")).toBeVisible()
|
||||
await view.dialog.getByRole("button", { name: /Browser profile/ }).click()
|
||||
await page.getByRole("option", { name: "Google Chrome · Work" }).click()
|
||||
await expect(view.options.first()).toHaveAttribute("data-site", "github.com")
|
||||
await expect(view.options.first()).toBeInViewport()
|
||||
await expect(view.record).toHaveAttribute("data-reads", "Default,Profile 1")
|
||||
})
|
||||
|
||||
story("starts from the site a passkey request came from, and stays open to say why an import left cookies behind", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5, site: { name: "github.com", choose: true }, partial: true })
|
||||
|
||||
await expect(view.options).toHaveCount(1)
|
||||
await expect(view.options).toHaveAttribute("data-site", "github.com")
|
||||
// The site the page belongs to is chosen already.
|
||||
await expect(view.options).toHaveAttribute("aria-selected", "true")
|
||||
await view.importButton.click()
|
||||
const status = view.dialog.getByRole("status")
|
||||
await expect(status).toHaveText("Imported 2 cookies. Not imported: 1.")
|
||||
await expect(view.record).toHaveAttribute("data-closed", "false")
|
||||
|
||||
// Status sits in the dialog body (not crammed into the footer), with top clearance and 0px edge drift.
|
||||
const layout = await view.dialog.evaluate((node) => {
|
||||
const body = node.querySelector('[data-slot="dialog-body"]')?.getBoundingClientRect()
|
||||
const title = node.querySelector('[data-slot="dialog-title"]')?.getBoundingClientRect()
|
||||
const closeSvg = node.querySelector('[data-slot="dialog-close-button"] svg')?.getBoundingClientRect()
|
||||
const search = node.querySelector('[data-component="text-input-v2"]')?.getBoundingClientRect()
|
||||
const select = node.querySelector('[data-component="select-v2"]')?.getBoundingClientRect()
|
||||
const msg = node.querySelector('[data-slot="dialog-body"] [role="status"]')?.getBoundingClientRect()
|
||||
const footerMsg = node.querySelector('[data-slot="dialog-footer"] [role="status"]')
|
||||
const footerBtns = Array.from(node.querySelectorAll('[data-slot="dialog-footer"] button'))
|
||||
const importBtn = footerBtns[footerBtns.length - 1]?.getBoundingClientRect()
|
||||
|
||||
return {
|
||||
footerHasStatus: footerMsg !== null,
|
||||
topClearanceSearch: body && search ? Math.round(search.top - body.top) : -1,
|
||||
topClearanceSelect: body && select ? Math.round(select.top - body.top) : -1,
|
||||
leftDeltas: title && search && msg ? [search.left - title.left, msg.left - title.left].map((v) => Math.round(v)) : [],
|
||||
rightDeltas:
|
||||
importBtn && closeSvg && select ? [closeSvg.right - importBtn.right, select.right - importBtn.right].map((v) => Math.round(v)) : [],
|
||||
}
|
||||
})
|
||||
|
||||
expect(layout.footerHasStatus).toBe(false)
|
||||
expect(layout.topClearanceSearch).toBeGreaterThanOrEqual(4)
|
||||
expect(layout.topClearanceSelect).toBeGreaterThanOrEqual(4)
|
||||
expect(layout.leftDeltas).toEqual([0, 0])
|
||||
expect(layout.rightDeltas).toEqual([0, 0])
|
||||
})
|
||||
|
||||
story("opened for a site, moves on to the browser profile that has exactly it, and chooses only that one", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5, site: { name: "google.com", choose: true } })
|
||||
|
||||
await expect(view.dialog.getByRole("button", { name: /Browser profile/ })).toContainText("Home")
|
||||
await expect(view.options).toHaveCount(2)
|
||||
await expect(view.dialog.locator('[data-site="google.com"]')).toHaveAttribute("aria-selected", "true")
|
||||
await expect(view.dialog.locator('[data-site="google.com.au"]')).toHaveAttribute("aria-selected", "false")
|
||||
// Counts are grouped for the app's language.
|
||||
await expect(view.dialog.locator('[data-site="google.com"]')).toContainText("120,000 cookies")
|
||||
})
|
||||
|
||||
story("a page's site that only another site contains chooses nothing, and says no sign-in was found", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5, site: { name: "hub.com", choose: true } })
|
||||
|
||||
// The search still shows github.com, which contains the name, but it is not the page's site.
|
||||
await expect(view.options).toHaveCount(1)
|
||||
await expect(view.options).toHaveAttribute("data-site", "github.com")
|
||||
await expect(view.options).toHaveAttribute("aria-selected", "false")
|
||||
await expect(view.dialog.getByText("No sign-in for hub.com was found in Google Chrome.")).toBeVisible()
|
||||
await expect(view.importButton).toBeDisabled()
|
||||
})
|
||||
|
||||
story("in a tab the agent drives, the page's site is shown but not chosen", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5, site: { name: "github.com", choose: false } })
|
||||
|
||||
await expect(view.options).toHaveCount(1)
|
||||
await expect(view.options).toHaveAttribute("data-site", "github.com")
|
||||
await expect(view.options).toHaveAttribute("aria-selected", "false")
|
||||
await expect(view.importButton).toBeDisabled()
|
||||
})
|
||||
|
||||
story("keeps the active row off the list's edges, and brings it into view from the search", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5_000 })
|
||||
|
||||
// How far the row is inside the list's frame, above and below.
|
||||
const inset = () =>
|
||||
view.dialog.locator("[data-active]").evaluate((row) => {
|
||||
const frame = row.closest('[role="listbox"]')?.parentElement?.closest(".overflow-hidden")?.getBoundingClientRect()
|
||||
const box = row.getBoundingClientRect()
|
||||
|
||||
return frame ? [Math.round(box.top - frame.top), Math.round(frame.bottom - box.bottom)] : []
|
||||
})
|
||||
|
||||
await view.list.focus()
|
||||
await page.keyboard.press("End")
|
||||
await expect.poll(async () => (await inset())[1]).toBeGreaterThanOrEqual(4)
|
||||
await page.keyboard.press("Home")
|
||||
await expect.poll(async () => (await inset())[0]).toBeGreaterThanOrEqual(4)
|
||||
|
||||
// A wheel scroll leaves the active first row out of view; ArrowDown from the search scrolls back to it.
|
||||
await view.list.hover()
|
||||
await page.mouse.wheel(0, 4_000)
|
||||
await expect(view.dialog.locator('[data-site="github.com"]')).not.toBeInViewport()
|
||||
await view.search.focus()
|
||||
await page.keyboard.press("ArrowDown")
|
||||
await expect(view.list).toBeFocused()
|
||||
await expect(view.dialog.locator('[data-site="github.com"]')).toBeInViewport()
|
||||
|
||||
// The count alone is a live region, so a selection is announced.
|
||||
await page.keyboard.press("Space")
|
||||
await expect(view.dialog.locator('[aria-live="polite"]')).toHaveText("4,999 of 5,000 selected")
|
||||
})
|
||||
|
||||
story("shows what the list is doing in its place, with a way to try again", async ({ page }) => {
|
||||
const held = await open(page, { sites: 5, hold: true })
|
||||
|
||||
await expect(held.dialog.getByRole("status")).toHaveText("Reading the sites in Google Chrome…")
|
||||
await expect(held.dialog.getByText(/selected/)).toBeHidden()
|
||||
await page.getByTestId("site-chooser-release").dispatchEvent("click")
|
||||
await expect(held.options).toHaveCount(5)
|
||||
await held.search.fill("nothing-like-this")
|
||||
await expect(held.dialog.getByRole("status")).toHaveText("No site matches your search.")
|
||||
})
|
||||
|
||||
story("says why a profile has no list, and reads it again on Try again", async ({ page }) => {
|
||||
const view = await open(page, { sites: "locked" })
|
||||
|
||||
await expect(view.dialog.getByRole("alert")).toHaveText("Google Chrome keeps its cookies locked while it runs. Quit Google Chrome, then import again.")
|
||||
await view.dialog.getByRole("button", { name: "Try again" }).click()
|
||||
await expect(view.record).toHaveAttribute("data-reads", "Default,Default")
|
||||
})
|
||||
|
||||
story("an empty profile says so", async ({ page }) => {
|
||||
const view = await open(page, { sites: 0 })
|
||||
|
||||
await expect(view.dialog.getByRole("status")).toHaveText("This profile has no sites to import.")
|
||||
await expect(view.importButton).toBeDisabled()
|
||||
})
|
||||
|
||||
story("opens on one sentence and Import all, which brings every site without the list", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5, reveal: false })
|
||||
|
||||
await expect(view.dialog.getByText("Copies cookies for all 5 sites. The other browser keeps its own.")).toBeVisible()
|
||||
await expect(view.list).toHaveCount(0)
|
||||
await expect(view.dialog.getByRole("button", { name: "Choose sites" })).toHaveAttribute("aria-expanded", "false")
|
||||
await view.importButton.click()
|
||||
// No list of sites: main imports the whole profile.
|
||||
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default" })])
|
||||
await expect(view.record).toHaveAttribute("data-closed", "true")
|
||||
})
|
||||
|
||||
story("empty fallback uses a compact fit dialog when no browsers are found", async ({ page }) => {
|
||||
await page.evaluate(
|
||||
async (input) => {
|
||||
const [{ mountSiteChooser }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
|
||||
|
||||
mountSiteChooser({ ui, scenario: { sites: 0, empty: true } })
|
||||
},
|
||||
{ modules },
|
||||
)
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Import sign-ins" })
|
||||
await expect(dialog.getByText("No other browser found on this computer")).toBeVisible()
|
||||
const box = await page.locator('[data-slot="dialog-container"]').boundingBox()
|
||||
expect(box && box.width <= 480 && box.height < 250).toBe(true)
|
||||
})
|
||||
|
||||
story("Choose sites shows the list in place, every site ticked, and the button then names how many it brings", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5, reveal: false })
|
||||
const choose = view.dialog.getByRole("button", { name: "Choose sites" })
|
||||
|
||||
await choose.click()
|
||||
await expect(choose).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(view.options).toHaveCount(5)
|
||||
await expect(view.dialog.getByText("5 of 5 selected")).toBeVisible()
|
||||
await expect(view.importButton).toHaveText("Import all")
|
||||
await view.dialog.locator('[data-site="github.com"]').click()
|
||||
await expect(view.importButton).toHaveText("Import 4 sites")
|
||||
// Ticking it again is everything again.
|
||||
await view.dialog.locator('[data-site="github.com"]').click()
|
||||
await expect(view.importButton).toHaveText("Import all")
|
||||
await view.dialog.locator('[data-site="github.com"]').click()
|
||||
await view.importButton.click()
|
||||
const sent = JSON.parse((await view.record.locator("li").textContent()) ?? "{}")
|
||||
expect(sent.sites).toHaveLength(4)
|
||||
expect(sent.sites).not.toContain("github.com")
|
||||
})
|
||||
|
||||
story("a list that Choose sites revealed after its sites loaded still draws the rows it scrolls to", async ({ page }) => {
|
||||
const view = await open(page, { sites: 5_000, reveal: false })
|
||||
|
||||
await view.dialog.getByRole("button", { name: "Choose sites" }).click()
|
||||
await expect(view.dialog.getByText("5,000 of 5,000 selected")).toBeVisible()
|
||||
await view.list.hover()
|
||||
await page.mouse.wheel(0, 4_000)
|
||||
await expect(view.dialog.locator('[data-site="github.com"]')).not.toBeInViewport()
|
||||
// 4,000 px down a list of 32 px rows.
|
||||
await expect(view.dialog.locator('[role="option"][aria-posinset="130"]')).toBeInViewport()
|
||||
})
|
||||
|
||||
story("keeps site names left to right in a right-to-left layout, the box at the start and long names cut at their start", async ({ page }) => {
|
||||
const view = await open(page, { sites: 6 }, "rtl")
|
||||
const row = view.dialog.locator('[data-site="xn--mnchen-3ya.de"]')
|
||||
const box = await row.locator('[data-slot="checkbox-v2-control"]').boundingBox()
|
||||
const name = await row.locator("bdi").first().boundingBox()
|
||||
const count = await row.getByText("5 cookies").boundingBox()
|
||||
|
||||
expect(box && name && count && box.x > name.x && name.x > count.x).toBe(true)
|
||||
const long = view.dialog.locator('[data-site$="example.co.uk"]').first().locator("span[title]")
|
||||
expect(await long.evaluate((element) => [getComputedStyle(element).direction, element.scrollWidth > element.clientWidth])).toEqual(["rtl", true])
|
||||
})
|
||||
|
||||
// The pane's sign-in bar says what an import brought for a few seconds, then goes by itself; Close ends it sooner.
|
||||
story("the sign-in bar's import confirmation goes by itself after 5 seconds, and Close ends it sooner", async ({ page }) => {
|
||||
await page.clock.install()
|
||||
await page.evaluate(
|
||||
async (input) => {
|
||||
const [{ mountSiteChooser }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
|
||||
|
||||
mountSiteChooser({ ui, scenario: { sites: 5, skipped: 318 }, offer: true })
|
||||
},
|
||||
{ modules },
|
||||
)
|
||||
const record = page.getByTestId("site-chooser-imports")
|
||||
const confirmation = page.getByRole("status").filter({ hasText: "Imported 10 cookies from Google Chrome" })
|
||||
const importing = page.getByRole("button", { name: /^Import from Google Chrome/ })
|
||||
|
||||
// Close ends it at once, and only once: the timer it no longer needs does not report a second close.
|
||||
await importing.click()
|
||||
await expect(confirmation).toBeVisible()
|
||||
await expect(record).toHaveAttribute("data-imported", "1")
|
||||
await confirmation.getByRole("button", { name: "Close", exact: true }).click()
|
||||
await expect(confirmation).toHaveCount(0)
|
||||
await expect(record).toHaveAttribute("data-closes", "1")
|
||||
await page.clock.runFor(10_000)
|
||||
await expect(record).toHaveAttribute("data-closes", "1")
|
||||
|
||||
// Left alone, it goes after 5 seconds.
|
||||
await importing.click()
|
||||
await expect(confirmation).toBeVisible()
|
||||
await page.clock.runFor(4_900)
|
||||
await expect(confirmation).toBeVisible()
|
||||
await expect(record).toHaveAttribute("data-closes", "1")
|
||||
await page.clock.runFor(200)
|
||||
await expect(confirmation).toHaveCount(0)
|
||||
await expect(record).toHaveAttribute("data-closes", "2")
|
||||
})
|
||||
|
|
@ -86,6 +86,7 @@ type Json = string | number | boolean | null | readonly Json[] | { readonly [key
|
|||
export { createComponent, createMemo, createRoot, createSignal, getOwner, onCleanup, runWithOwner, useDialog }
|
||||
|
||||
const layout: BuiltinLayout = {
|
||||
fitsSide: () => true,
|
||||
narrow: () => false,
|
||||
ready: () => true,
|
||||
open() {},
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import type {
|
|||
SessionScreen,
|
||||
SetupContext,
|
||||
} from "@opencode/plugin/gui"
|
||||
import type { BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
|
||||
import type { BuiltinContext, BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
|
||||
import type { Bridge, BridgeMessage, EnableState, Installed } from "@opencode/plugin/gui/host"
|
||||
import type { JSHandle } from "@playwright/test"
|
||||
import type { mountCodeBlocks, mountThemes } from "./plugin-host.fixture"
|
||||
|
|
@ -1260,6 +1260,34 @@ story(
|
|||
},
|
||||
)
|
||||
|
||||
story("a scoped contract binds the consuming instance, not the plugin that happens to call a saved method", async ({ page }) => {
|
||||
const result = await page.evaluate(async (fixture) => {
|
||||
const { Contract, mountPlugins, until } = await import(fixture)
|
||||
const token: Contract<() => string> = Contract.define("provider.scoped")
|
||||
const reads = new Map<string, () => Live<() => string>>()
|
||||
|
||||
const host = mountPlugins({ definitions: [
|
||||
{ id: "provider", windowEntry: async () => ({ default: (ctx: BuiltinContext) =>
|
||||
ctx.provideFor(token, (consumer) => () => consumer) }) },
|
||||
...["one", "two"].map(id => ({ id, windowEntry: async () => ({ default: (ctx: Context) => { reads.set(id, ctx.use(token)) } }) })),
|
||||
] })
|
||||
|
||||
await until(() => ["one", "two"].every(id => reads.get(id)?.().status === "active"))
|
||||
|
||||
const owners = ["one", "two"].map(id => {
|
||||
const value = reads.get(id)?.()
|
||||
|
||||
return value?.status === "active" && value.value()
|
||||
})
|
||||
|
||||
host.unmount()
|
||||
|
||||
return owners
|
||||
}, fixture)
|
||||
|
||||
expect(result).toEqual(["one", "two"])
|
||||
})
|
||||
|
||||
story("a contract component reads its provider context and preserves reactive props", async ({ page }) => {
|
||||
const result = await page.evaluate(async (fixture) => {
|
||||
const { bindPlugin, createComponent, createSignal, Contract, mountPlugins, Slot, until, usePlugin } = await import(
|
||||
|
|
|
|||
79
packages/app/component-tests/session-containment.fixture.tsx
Normal file
79
packages/app/component-tests/session-containment.fixture.tsx
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { createSignal, Show } from "solid-js"
|
||||
import { render } from "solid-js/web"
|
||||
import type { SessionMessageAssistantText, SessionMessageAssistantTool } from "@opencode/client/promise"
|
||||
import { activePermissionRequest, permissionPendingDocument } from "@opencode/session-ui/storybook"
|
||||
import { timelinePresets } from "@opencode/session-ui/timeline/detail"
|
||||
import { DialogProvider } from "@opencode/ui/context/dialog"
|
||||
import { ThemeProvider } from "@opencode/ui/theme"
|
||||
import { LanguageProvider, UiI18nBridge } from "../src/runtime/i18n/language"
|
||||
import { SettingsProvider } from "../src/settings/model"
|
||||
import { SessionPreview } from "../src/session/story-model"
|
||||
|
||||
const [pending, setPending] = createSignal(true)
|
||||
|
||||
// The complete session workspace with a pending tool permission, and one authored message in its history: as the
|
||||
// assistant's text, or as the output of a tool whose renderer shows Markdown.
|
||||
export function mountContainment(markup: string, delivery: "text" | "tool") {
|
||||
const host = document.createElement("div")
|
||||
host.dataset.testid = "containment-fixture"
|
||||
host.style.cssText = "position:fixed;inset:0"
|
||||
document.body.append(host)
|
||||
document.getElementById("story-root")?.style.setProperty("display", "none")
|
||||
const [user, assistant] = permissionPendingDocument.messages
|
||||
|
||||
if (!user || assistant?.type !== "assistant") throw new Error("The permission document changed shape.")
|
||||
const created = assistant.time.created
|
||||
const text: SessionMessageAssistantText = { type: "text", text: markup }
|
||||
|
||||
const tool: SessionMessageAssistantTool = {
|
||||
type: "tool",
|
||||
id: "tool_containment_list",
|
||||
name: "list",
|
||||
state: { status: "completed", input: { path: "." }, content: [{ type: "text", text: markup }] },
|
||||
time: { created: created + 10, ran: created + 20, completed: created + 30 },
|
||||
}
|
||||
|
||||
const history = {
|
||||
...permissionPendingDocument,
|
||||
messages: [user, { ...assistant, content: [delivery === "text" ? text : tool, ...assistant.content] }],
|
||||
}
|
||||
|
||||
// Tools as their own rows, so the tool's Markdown output can be opened.
|
||||
const detail = timelinePresets[0].value
|
||||
|
||||
// The preview keeps its first request, so the answered state is a fresh workspace with the same history.
|
||||
render(
|
||||
() => (
|
||||
<ThemeProvider>
|
||||
<LanguageProvider locale="en">
|
||||
<UiI18nBridge>
|
||||
<SettingsProvider>
|
||||
<DialogProvider>
|
||||
<Show
|
||||
when={pending()}
|
||||
fallback={
|
||||
<SessionPreview title="Containment" description="opencode" document={history} timelineDetail={detail} />
|
||||
}
|
||||
>
|
||||
<SessionPreview
|
||||
title="Containment"
|
||||
description="opencode"
|
||||
document={history}
|
||||
timelineDetail={detail}
|
||||
request={{ type: "permission", value: activePermissionRequest }}
|
||||
/>
|
||||
</Show>
|
||||
</DialogProvider>
|
||||
</SettingsProvider>
|
||||
</UiI18nBridge>
|
||||
</LanguageProvider>
|
||||
</ThemeProvider>
|
||||
),
|
||||
host,
|
||||
)
|
||||
}
|
||||
|
||||
/** The permission is answered: the dock gives way to the composer. */
|
||||
export function answerPermission() {
|
||||
setPending(false)
|
||||
}
|
||||
145
packages/app/component-tests/session-containment.spec.ts
Normal file
145
packages/app/component-tests/session-containment.spec.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import type { Locator, Page } from "@playwright/test"
|
||||
import { expect, sourceURL, story } from "../../stories/playwright/story"
|
||||
|
||||
const fixture = sourceURL(new URL("./session-containment.fixture.tsx", import.meta.url))
|
||||
|
||||
const marker = "Containment sample"
|
||||
|
||||
// Authored layout and top-layer markup from the chat link security review (F2, its confirmation pass, and N3).
|
||||
const inputs = {
|
||||
"block anchor card": `<a href="obsidian://open?vault=x" style="display:block;color:inherit;text-decoration:none;cursor:text;padding:400px 0"><div>${marker}: the whole answer</div></a>`,
|
||||
"fixed transparent anchor": `${marker}<a href="obsidian://open?vault=x" style="position:fixed;inset:0;opacity:0;z-index:2147483647">x</a>`,
|
||||
"popover cover": `${marker}<button popovertarget="user-content-p">Show details</button><div id="p" popover="manual" style="position:fixed;inset:0;width:100vw;height:100vh;max-width:none;max-height:none;margin:0;border:0;background:#fff;color:#000;pointer-events:none">COVER</div>`,
|
||||
"invoker dialog": `${marker}<button command="show-modal" commandfor="user-content-d">Show details</button><dialog id="d" style="width:100vw;height:100vh;max-width:none;max-height:none;margin:0;background:#fff">COVER</dialog>`,
|
||||
"fixed tint": `${marker}<div style="position:fixed;inset:0;background:red;opacity:.4;pointer-events:none">x</div>`,
|
||||
"author-sized math": `${marker} $\\raisebox{-40em}{\\colorbox{white}{\\rule{60em}{30em}}}$`,
|
||||
// A math fence renders as display math, placed through the same slot as a $$ formula.
|
||||
"author-sized math fence": `${marker}\n\n\`\`\`math\n\\raisebox{-40em}{\\colorbox{white}{\\rule{60em}{30em}}}\n\`\`\`\n`,
|
||||
}
|
||||
|
||||
const legitimate = `${marker}\n\n| West | East |\n| :-- | --: |\n| Lettuce | Ranch |\n\n<img width="96" alt="Sample image" src="https://example.invalid/sample.png">\n\n<span style="color:teal">Teal text</span>`
|
||||
|
||||
for (const delivery of ["text", "tool"] as const) {
|
||||
for (const [name, markup] of Object.entries(inputs)) {
|
||||
story(`keeps ${name} inside its message as ${delivery}`, async ({ mount, page }) => {
|
||||
const root = await open(page, mount, markup, delivery)
|
||||
|
||||
if (name.endsWith("math fence")) await expect(root.locator(".katex-display")).toHaveCount(1)
|
||||
await press(root)
|
||||
await expectContained(page, root, delivery)
|
||||
})
|
||||
}
|
||||
|
||||
story(`renders legitimate authored markup normally as ${delivery}`, async ({ mount, page }) => {
|
||||
const root = await open(page, mount, legitimate, delivery)
|
||||
await expect(root.locator("th").filter({ hasText: "East" })).toHaveAttribute("align", "right")
|
||||
await expect(root.locator('img[alt="Sample image"]')).toHaveAttribute("width", "96")
|
||||
await expect(root.locator('img[alt="Sample image"]')).toHaveJSProperty("width", 96)
|
||||
await expect(root.getByText("Teal text", { exact: true })).toHaveCSS("color", "rgb(0, 128, 128)")
|
||||
await expectContained(page, root, delivery)
|
||||
})
|
||||
}
|
||||
|
||||
async function open(page: Page, mount: (id: string) => Promise<Locator>, markup: string, delivery: "text" | "tool") {
|
||||
await page.route("https://example.invalid/**", (route) =>
|
||||
route.fulfill({ contentType: "image/png", body: Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a4ioAAAAASUVORK5CYII=", "base64") }),
|
||||
)
|
||||
await page.setViewportSize({ width: 1280, height: 800 })
|
||||
await mount("ui-line-comment--editor")
|
||||
await page.evaluate(async ({ fixture, markup, delivery }) => {
|
||||
const { mountContainment } = await import(fixture)
|
||||
mountContainment(markup, delivery)
|
||||
}, { fixture, markup, delivery })
|
||||
await expect(page.getByTestId("containment-fixture").getByRole("button", { name: "Allow once" })).toBeVisible()
|
||||
|
||||
return message(page, delivery)
|
||||
}
|
||||
|
||||
// The tool output sits in a collapsed tool row.
|
||||
async function message(page: Page, delivery: "text" | "tool") {
|
||||
const host = page.getByTestId("containment-fixture")
|
||||
const root = host.locator('[data-component="markdown"]').filter({ hasText: marker }).last()
|
||||
|
||||
for (let step = 0; delivery === "tool" && step < 1 && !(await root.isVisible()); step++)
|
||||
await host.locator('button[data-slot="collapsible-trigger"][aria-expanded="false"]').filter({ hasText: "List" }).first().click()
|
||||
await expect(root).toBeVisible()
|
||||
await page.evaluate(() => document.fonts.ready.then(() => undefined))
|
||||
|
||||
return root
|
||||
}
|
||||
|
||||
// A person clicks whatever the message offers, as the cover recipes require.
|
||||
async function press(root: Locator) {
|
||||
for (const button of await root.locator("button").all()) await button.click({ force: true, timeout: 2_000 }).catch(() => undefined)
|
||||
}
|
||||
|
||||
async function expectContained(page: Page, root: Locator, delivery: "text" | "tool") {
|
||||
const host = page.getByTestId("containment-fixture")
|
||||
const dock = await frontmost(page, host.getByRole("button", { name: "Allow once" }))
|
||||
const contained = await layout(page, root)
|
||||
// Answered, the dock gives way to the composer in a fresh render of the same history; press the message again.
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { answerPermission } = await import(fixture)
|
||||
answerPermission()
|
||||
}, fixture)
|
||||
const composer = host.locator('[data-component="composer-editor"]').first()
|
||||
await expect(composer).toBeVisible()
|
||||
await press(await message(page, delivery))
|
||||
|
||||
expect({ ...contained, dock, composer: await frontmost(page, composer) }).toEqual({
|
||||
escaped: [],
|
||||
topLayer: 0,
|
||||
dock: true,
|
||||
composer: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Whether hit testing at the control's centre reaches the control first.
|
||||
async function frontmost(page: Page, control: Locator) {
|
||||
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))))
|
||||
const box = await control.boundingBox()
|
||||
|
||||
if (!box) return false
|
||||
|
||||
return control.evaluate((element, point) => element.contains(document.elementsFromPoint(point.x, point.y)[0] ?? null), {
|
||||
x: box.x + box.width / 2,
|
||||
y: box.y + box.height / 2,
|
||||
})
|
||||
}
|
||||
|
||||
// Descendants painted outside the message, and message content in the top layer.
|
||||
async function layout(page: Page, root: Locator) {
|
||||
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))))
|
||||
|
||||
return root.evaluate((message) => {
|
||||
const bounds = message.getBoundingClientRect()
|
||||
|
||||
// A descendant's painted area: its box, cut by every clipping ancestor inside the message.
|
||||
const painted = (node: Element) => {
|
||||
const box = node.getBoundingClientRect()
|
||||
const area = { left: box.left, top: box.top, right: box.right, bottom: box.bottom }
|
||||
|
||||
for (let parent = node.parentElement; parent && parent !== message; parent = parent.parentElement) {
|
||||
if (getComputedStyle(parent).overflow === "visible") continue
|
||||
const clip = parent.getBoundingClientRect()
|
||||
area.left = Math.max(area.left, clip.left)
|
||||
area.top = Math.max(area.top, clip.top)
|
||||
area.right = Math.min(area.right, clip.right)
|
||||
area.bottom = Math.min(area.bottom, clip.bottom)
|
||||
}
|
||||
|
||||
return area
|
||||
}
|
||||
|
||||
const escaped = Array.from(message.querySelectorAll("*"))
|
||||
.filter((node) => !node.closest(".katex-mathml"))
|
||||
.map((node) => ({ node, area: painted(node) }))
|
||||
.filter(({ area }) => area.right > area.left && area.bottom > area.top)
|
||||
.filter(({ area }) => area.left < bounds.left - 1 || area.top < bounds.top - 1 || area.right > bounds.right + 1 || area.bottom > bounds.bottom + 1)
|
||||
.map(({ node }) => node.localName)
|
||||
|
||||
const topLayer = Array.from(document.querySelectorAll(":popover-open, dialog[open]")).filter((node) => message.contains(node)).length
|
||||
|
||||
return { escaped: escaped.slice(0, 5), topLayer }
|
||||
})
|
||||
}
|
||||
|
|
@ -97,6 +97,14 @@ for (const view of ["desktop", "mobile"] as const) {
|
|||
|
||||
if (view === "desktop") await openReviewLauncher(panel)
|
||||
await expect(panel.getByText("Track, review, and undo changes in this project")).toBeVisible()
|
||||
|
||||
if (view === "desktop") {
|
||||
const toggle = panel.getByRole("button", {name:"Toggle file tree"})
|
||||
|
||||
if (await toggle.getAttribute("aria-expanded") === "false") await toggle.click()
|
||||
await expect(panel.getByText("No changed files. Use Open file to browse the workspace.")).toBeVisible()
|
||||
}
|
||||
|
||||
await expect(panel.getByRole("button", { name: "Git changes" })).toHaveCount(0)
|
||||
const init = panel.getByRole("button", { name: "Create Git repository" })
|
||||
await init.click()
|
||||
|
|
@ -495,6 +503,12 @@ test("context closes the side region only when its button opened it", async ({ p
|
|||
await panel.getByRole("button", { name: /^Review/ }).click()
|
||||
await expect(panel.locator("#session-side-panel-review-tab")).toHaveAttribute("aria-selected", "true")
|
||||
await context.click()
|
||||
// Under a New tab view Context is not what the region shows, so its button shows it rather than closing it unseen.
|
||||
await panel.getByRole("button", { name: "Add tab", exact: true }).click()
|
||||
await expect(newTab).toHaveAttribute("aria-selected", "true")
|
||||
await contextButton.click()
|
||||
await expect(newTab).toHaveCount(0)
|
||||
await expect(context).toHaveAttribute("aria-selected", "true")
|
||||
await contextButton.click()
|
||||
await expect(context).toHaveCount(0)
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "true")
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
".": "./src/index.ts",
|
||||
"./desktop": "./src/desktop.ts",
|
||||
"./desktop-menu": "./src/shell/commands/desktop-menu.ts",
|
||||
"./loopback": "./src/runtime/server/loopback.ts",
|
||||
"./i18n/desktop-native": "./src/runtime/i18n/desktop-native.ts",
|
||||
"./vite": "./vite.js",
|
||||
"./index.css": "./src/index.css"
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ build on the e2e mock server, so they need no backend.
|
|||
| `diff.bench.ts` | open a long diff · open a huge diff · return to a long diff | A 1,559-line diff, highlighted; a 15,599-line one, plain. |
|
||||
| `composer.bench.ts` | type in a large draft · move the cursor in it · recall a prompt from history | A 44,000-character saved draft; 100 prompts with screenshots. |
|
||||
| `docks.bench.ts` | open and close request docks | A permission dock and an MCP elicitation over a 20-turn session. |
|
||||
| `send.bench.ts` | send a prompt | Enter until the prompt request reaches the server, 20 turns. |
|
||||
| `question.bench.ts` | switch questions | The new question dock with its motion on: five questions. |
|
||||
| `desktop.bench.ts` | idle | The packaged desktop app, every process, doing nothing for 5 s. |
|
||||
|
||||
|
|
|
|||
|
|
@ -76,6 +76,8 @@ type TimelineOptions = {
|
|||
tools?: SessionMessageAssistant["content"]
|
||||
/** Events arrive from a real SSE endpoint (`source`); otherwise the mock's own stream stays idle. */
|
||||
stream?: boolean
|
||||
/** Called each time a prompt request reaches the server. */
|
||||
onPrompt?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -130,6 +132,7 @@ export async function mockTimelineSession(page: Page, options: TimelineOptions)
|
|||
vcsDiff: options.vcsDiff,
|
||||
sessionStatus: options.busy ? { [sessionID]: { type: "busy" } } : undefined,
|
||||
pageMessages: () => ({ items: messages }),
|
||||
onPrompt: options.onPrompt,
|
||||
})
|
||||
await page.addInitScript((general) => localStorage.setItem("settings.v3", JSON.stringify({ general })), {
|
||||
editToolPartsExpanded: true,
|
||||
|
|
|
|||
54
packages/app/perf/send.bench.ts
Normal file
54
packages/app/perf/send.bench.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// How long a prompt takes to leave the window: from Enter until its request reaches the server, in a 20-turn session.
|
||||
// Nothing here waits on a server, so the time is the composer's own: its submit machine, what the plugins prepare for
|
||||
// the session's next step, the selection's commit and the request it builds. At 1366x768.
|
||||
import { bench, web } from "@hona/strobe"
|
||||
import { cached } from "./fixtures/mock"
|
||||
import { composer, mockTimelineSession, timeline } from "./fixtures/timeline"
|
||||
|
||||
// The runs waiting for their request to reach the server: one at a time.
|
||||
const waiting: (() => void)[] = []
|
||||
|
||||
const arrived = () => new Promise<void>((resolve) => void waiting.push(resolve))
|
||||
|
||||
export default bench({
|
||||
targets: {
|
||||
web: web({
|
||||
expect: { title: "OpenCode" },
|
||||
viewport: { width: 1366, height: 768 },
|
||||
prepare: (ctx) =>
|
||||
mockTimelineSession(cached(ctx), {
|
||||
server: new URL(ctx.url).origin,
|
||||
historyTurns: 20,
|
||||
onPrompt: () => waiting.splice(0).forEach((resolve) => resolve()),
|
||||
}),
|
||||
url: ({ prepared }) => prepared.path,
|
||||
}),
|
||||
},
|
||||
|
||||
async setup({ page }) {
|
||||
await page.waitFor(timeline, { timeout: 60_000 })
|
||||
await page.waitFor(composer)
|
||||
await page.click(composer)
|
||||
await page.idle()
|
||||
},
|
||||
|
||||
cases: {
|
||||
// Typing is not the send: the phase runs from the Enter key to the request's arrival. Each run adds one prompt to
|
||||
// the session, as a person's next message does.
|
||||
"send a prompt": {
|
||||
primary: "phase.send",
|
||||
metrics: ["main.work", "net.requests{/api/session/*/prompt}"],
|
||||
resetCheck: false,
|
||||
async run({ page, phase }) {
|
||||
await page.type(composer, "Tighten the error message.", { burst: true })
|
||||
const request = arrived()
|
||||
|
||||
await phase("send", async () => {
|
||||
await page.press("Enter")
|
||||
await request
|
||||
})
|
||||
await page.idle()
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
|
@ -96,6 +96,8 @@ export type ComposerSession = {
|
|||
location: { command: Pick<Data["location"]["command"], "list"> }
|
||||
session: {
|
||||
prompt: (input: Parameters<Data["session"]["prompt"]>[0]) => ReturnType<Data["session"]["prompt"]>
|
||||
// Runs a request in the session's send chain, after the sends made before it have settled.
|
||||
sequence: Data["session"]["sequence"]
|
||||
setStatus: Data["session"]["setStatus"]
|
||||
// Records an accepted user send so the desktop list promotes the session immediately.
|
||||
acceptSend: (sessionID: string) => void
|
||||
|
|
|
|||
|
|
@ -132,6 +132,7 @@ export function QuoteCommentEditor(props: {
|
|||
})
|
||||
}}
|
||||
data-component="composer-quote-comment"
|
||||
data-floating-overlay
|
||||
data-prevent-autofocus
|
||||
class="fixed z-50"
|
||||
style={{
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ const session: ComposerSession = {
|
|||
payload: { text: value.text },
|
||||
delivery: value.delivery ?? "steer",
|
||||
}),
|
||||
sequence: (_sessionID, send) => send(),
|
||||
setStatus() {},
|
||||
acceptSend() {},
|
||||
},
|
||||
|
|
@ -128,6 +129,12 @@ const states = {
|
|||
running: replay([{ type: "submit", snapshot: snapshot({ clientCommand: () => undefined }), done }]).state,
|
||||
preparing: replay([{ type: "submit", snapshot: snapshot(), done }]).state,
|
||||
"handing-off": replay([{ type: "submit", snapshot: snapshot(), done }, started(1)]).state,
|
||||
sending: replay([
|
||||
{ type: "submit", snapshot: snapshot(), done },
|
||||
started(1),
|
||||
{ type: "handoff.ready", attempt: 1, prompt: undefined },
|
||||
]).state,
|
||||
quoting: replay([{ type: "quote", snapshot: quoteSnapshot(), done }]).state,
|
||||
}
|
||||
|
||||
describe("composer submit machine", () => {
|
||||
|
|
@ -147,6 +154,7 @@ describe("composer submit machine", () => {
|
|||
session,
|
||||
ready,
|
||||
},
|
||||
{ type: "gate.settled", attempt: 1 },
|
||||
{ type: "handoff.ready", attempt: 1, prompt: undefined },
|
||||
])
|
||||
|
||||
|
|
@ -253,6 +261,7 @@ describe("composer submit machine", () => {
|
|||
[
|
||||
{ type: "hold.loaded", attempt: 1, selection, commands: [{ name: "review" }] },
|
||||
started(1),
|
||||
{ type: "gate.settled", attempt: 1 },
|
||||
{ type: "handoff.ready", attempt: 1, prompt: undefined },
|
||||
],
|
||||
shown.state,
|
||||
|
|
@ -305,6 +314,97 @@ describe("composer submit machine", () => {
|
|||
])
|
||||
})
|
||||
|
||||
// What the plugins prepare for a prompt or a server command is part of sending it. Until it is ready nothing of the
|
||||
// send has reached the server, the composer takes no other send, and Stop cancels this one.
|
||||
test("a send whose gate is still pending when the composer clears keeps the composer until its request may leave", () => {
|
||||
const handing = states["handing-off"]
|
||||
expect(handing).toMatchObject({ type: "handing-off", gate: "pending" })
|
||||
|
||||
const cleared = transitionComposerSubmit(handing, { type: "handoff.ready", attempt: 1, prompt: undefined })
|
||||
expect(cleared.state).toEqual({ type: "sending", attempt: 1, done })
|
||||
// The composer clears, as the prompt already shows in its Session, and the submit has not settled yet.
|
||||
expect(cleared.effects.map((effect) => effect.type)).toEqual(["composer.clear"])
|
||||
expect(composerSubmitView(cleared.state)).toEqual({ held: true, busy: true, canSubmit: false })
|
||||
|
||||
expect(transitionComposerSubmit(cleared.state, { type: "gate.settled", attempt: 1 })).toEqual({
|
||||
state: { type: "idle", attempt: 1 },
|
||||
effects: [{ type: "done", done, sent: true }],
|
||||
})
|
||||
})
|
||||
|
||||
test("a gate that settles before the composer clears lets the send through as before", () => {
|
||||
const settled = transitionComposerSubmit(states["handing-off"], { type: "gate.settled", attempt: 1 })
|
||||
expect(settled).toMatchObject({ state: { type: "handing-off", gate: "settled" }, effects: [] })
|
||||
|
||||
const cleared = transitionComposerSubmit(settled.state, { type: "handoff.ready", attempt: 1, prompt: undefined })
|
||||
expect(cleared.state).toEqual({ type: "idle", attempt: 1 })
|
||||
expect(cleared.effects.map((effect) => effect.type)).toEqual(["composer.clear", "done"])
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ name: "a prompt", input: {}, gated: true },
|
||||
{ name: "a server command", input: { text: "/review", commands: [{ name: "review" }] }, gated: true },
|
||||
{ name: "a shell command", input: { mode: "shell" }, gated: false },
|
||||
] satisfies { name: string; input: Partial<SubmitSnapshot>; gated: boolean }[])("$name waits on the gate: $gated", (row) => {
|
||||
const result = replay([{ type: "submit", snapshot: snapshot(row.input), done }, started(1)])
|
||||
|
||||
expect(result.effects.find((effect) => effect.type === "handoff")).toMatchObject({ gated: row.gated })
|
||||
expect(result.state).toMatchObject({ type: "handing-off", gate: row.gated ? "pending" : "none" })
|
||||
// A send with no gate settles as it always did.
|
||||
expect(
|
||||
transitionComposerSubmit(result.state, { type: "handoff.ready", attempt: 1, prompt: undefined }).state.type,
|
||||
).toBe(row.gated ? "sending" : "idle")
|
||||
})
|
||||
|
||||
test("Stop cancels a send that still waits on the gate, and interrupts the Session only when none does", () => {
|
||||
const cancel: ComposerSubmitTransition = {
|
||||
state: { type: "idle", attempt: 1 },
|
||||
effects: [
|
||||
{ type: "send.cancel", attempt: 1 },
|
||||
{ type: "done", done, sent: false },
|
||||
],
|
||||
}
|
||||
|
||||
expect(transitionComposerSubmit(states.sending, { type: "stop" })).toEqual(cancel)
|
||||
expect(transitionComposerSubmit(states["handing-off"], { type: "stop" })).toEqual(cancel)
|
||||
|
||||
// A quote's own send settles the run, once it fails as cancelled.
|
||||
const quoting = transitionComposerSubmit(states.quoting, { type: "stop" })
|
||||
expect(quoting).toEqual({ state: states.quoting, effects: [{ type: "send.cancel", attempt: 1 }] })
|
||||
expect(transitionComposerSubmit(quoting.state, { type: "run.settled", attempt: 1, sent: false })).toEqual({
|
||||
state: { type: "idle", attempt: 1 },
|
||||
effects: [{ type: "done", done, sent: false }],
|
||||
})
|
||||
|
||||
// Once the gate settled the request may have left: Stop is for the Session again, and never both.
|
||||
for (const state of [states["handing-off"], states.quoting]) {
|
||||
const settled = transitionComposerSubmit(state, { type: "gate.settled", attempt: 1 }).state
|
||||
expect(transitionComposerSubmit(settled, { type: "stop" })).toEqual({ state: settled, effects: [{ type: "interrupt" }] })
|
||||
}
|
||||
|
||||
expect(transitionComposerSubmit(states.running, { type: "stop" }).effects).toEqual([{ type: "interrupt" }])
|
||||
})
|
||||
|
||||
test("a gate result for a cancelled or another send changes nothing", () => {
|
||||
const cancelled = transitionComposerSubmit(states.sending, { type: "stop" }).state
|
||||
|
||||
for (const state of [cancelled, states.sending, states["handing-off"], states.quoting, states.preparing, states.running]) {
|
||||
const attempt = state === cancelled ? 1 : 2
|
||||
expect(transitionComposerSubmit(state, { type: "gate.settled", attempt }).state).toBe(state)
|
||||
}
|
||||
|
||||
// The next send's gate is its own.
|
||||
const next = replay([{ type: "submit", snapshot: snapshot(), done }, started(2), { type: "gate.settled", attempt: 1 }], cancelled)
|
||||
expect(next.state).toMatchObject({ type: "handing-off", attempt: 2, gate: "pending" })
|
||||
})
|
||||
|
||||
test("a composer that unmounts while its send waits on the gate leaves the send to finish", () => {
|
||||
expect(transitionComposerSubmit(states.sending, { type: "unmounted" })).toEqual({
|
||||
state: { type: "idle", attempt: 1 },
|
||||
effects: [{ type: "done", done, sent: true }],
|
||||
})
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ name: "a slash command", input: { text: "/review" } },
|
||||
{ name: "a shell command", input: { mode: "shell" } },
|
||||
|
|
|
|||
|
|
@ -40,8 +40,11 @@ export type CapturedDraft = {
|
|||
sources: { key: string; source: QuoteSource }[]
|
||||
}
|
||||
|
||||
/** A prompt sent before the composer cleared; `settled` restores the draft through `restore` when it fails. */
|
||||
export type PromptSend = { settled: (restore: () => boolean) => Promise<boolean> }
|
||||
/**
|
||||
* A prompt sent before the composer cleared; `settled` restores the draft through `restore` when it fails, which
|
||||
* hears whether the send was cancelled rather than refused.
|
||||
*/
|
||||
export type PromptSend = { settled: (restore: (cancelled: boolean) => boolean) => Promise<boolean> }
|
||||
|
||||
/** Settles the caller of `submit` or `submitQuote`; `sent` is false when nothing was sent. */
|
||||
export type SubmitDone = (sent: boolean) => void
|
||||
|
|
@ -49,14 +52,22 @@ export type SubmitDone = (sent: boolean) => void
|
|||
/** A held prompt that already shows in its Session's timeline; `cleared` is the composer it left, once cleared. */
|
||||
export type ShownHold = { session: ComposerSession; cleared: Prompt | undefined }
|
||||
|
||||
/**
|
||||
* What a send waits for before its request may leave: whatever the plugins prepare for a prompt or a server command,
|
||||
* such as attaching to the session. `none` for a send that starts no step, as a shell command. While `pending`,
|
||||
* nothing of the send has reached the server, so Stop cancels the send itself.
|
||||
*/
|
||||
export type SendGate = "none" | "pending" | "settled"
|
||||
|
||||
export type ComposerSubmitState =
|
||||
| { type: "idle"; attempt: number }
|
||||
// A send pressed while a cold Location loads its agents and models; it goes through once they load. A prompt to a
|
||||
// Session shows in its timeline at once and leaves the composer (`shown`); any other send waits in the composer,
|
||||
// where an edit cancels it.
|
||||
| { type: "held"; attempt: number; snapshot: SubmitSnapshot; shown: ShownHold | undefined; done: SubmitDone }
|
||||
// A client command or a quote runs; neither takes the draft, but the composer submits nothing else meanwhile.
|
||||
| { type: "running"; attempt: number; done: SubmitDone }
|
||||
// A client command or a quote runs; neither takes the draft, but the composer submits nothing else meanwhile. A quote
|
||||
// is a prompt, so it waits on the gate as one does.
|
||||
| { type: "running"; attempt: number; gate: SendGate; done: SubmitDone }
|
||||
// Image attachments resolve and, for a new Session, the Session starts. Nothing is sent yet. `cleared` is the
|
||||
// composer a shown hold already cleared.
|
||||
| {
|
||||
|
|
@ -79,8 +90,12 @@ export type ComposerSubmitState =
|
|||
comments: PromptHistoryComment[]
|
||||
cleared: Prompt | undefined
|
||||
session: ComposerSession
|
||||
gate: SendGate
|
||||
done: SubmitDone
|
||||
}
|
||||
// The composer cleared and the send shows in its Session, but its request still waits on the gate. The composer
|
||||
// submits nothing else, so sends leave in the order they were made, and Stop cancels this one.
|
||||
| { type: "sending"; attempt: number; done: SubmitDone }
|
||||
|
||||
export type SubmitSnapshot = {
|
||||
draft: CapturedDraft
|
||||
|
|
@ -138,12 +153,19 @@ export type ComposerSubmitEvent =
|
|||
| { type: "session.retargeted"; attempt: number; target: ComposerStateTarget; preserveDraft: boolean }
|
||||
| { type: "submit.aborted"; attempt: number }
|
||||
| { type: "handoff.ready"; attempt: number; prompt: PromptSend | undefined }
|
||||
/** What the send of `attempt` waited for is ready, or timed out: its request may leave. */
|
||||
| { type: "gate.settled"; attempt: number }
|
||||
|
||||
export type ComposerSubmitEffect =
|
||||
| { type: "done"; done: SubmitDone; sent: boolean }
|
||||
| { type: "notify.missing-selection" }
|
||||
| { type: "notify.unqueueable" }
|
||||
| { type: "interrupt" }
|
||||
/**
|
||||
* Cancels the send of `attempt` before its request leaves: it is removed from its Session, and a draft the composer
|
||||
* already gave up for it comes back.
|
||||
*/
|
||||
| { type: "send.cancel"; attempt: number }
|
||||
| { type: "submit.retry"; alternate: boolean; first?: boolean; done: SubmitDone }
|
||||
/** Shows a held prompt in its Session's timeline and clears the composer it came from. */
|
||||
| { type: "hold.show"; attempt: number; session: ComposerSession; snapshot: SubmitSnapshot }
|
||||
|
|
@ -174,6 +196,8 @@ export type ComposerSubmitEffect =
|
|||
value: ComposerSubmission
|
||||
/** A prompt shows in the Session as soon as it starts, before the composer clears. */
|
||||
sendFirst: boolean
|
||||
/** The send waits on the gate: the driver starts it and reports `gate.settled`. */
|
||||
gated: boolean
|
||||
ready: Promise<void>
|
||||
complete?: () => Promise<void>
|
||||
}
|
||||
|
|
@ -182,6 +206,7 @@ export type ComposerSubmitEffect =
|
|||
draft: CapturedDraft
|
||||
value: ComposerSubmission
|
||||
kind: SubmissionKind
|
||||
attempt: number
|
||||
comments: PromptHistoryComment[]
|
||||
session: ComposerSession
|
||||
prompt: PromptSend | undefined
|
||||
|
|
@ -203,12 +228,28 @@ export function transitionComposerSubmit(
|
|||
|
||||
if (event.type === "quote") return quote(state, event.snapshot, event.done)
|
||||
|
||||
// Stopping a held send cancels it and leaves the prompt in the composer.
|
||||
if (event.type === "stop")
|
||||
return state.type === "held" ? cancelHold(state, []) : { state, effects: [{ type: "interrupt" }] }
|
||||
if (event.type === "stop") return stop(state)
|
||||
|
||||
// A promoted new-session composer unmounts while its first prompt hands off, so only a held send ends here.
|
||||
if (event.type === "unmounted") return state.type === "held" ? cancelHold(state, []) : unchanged(state)
|
||||
// A promoted new-session composer unmounts while its first prompt hands off, so only a held send ends here. A send
|
||||
// that waits on the gate goes on without its composer.
|
||||
if (event.type === "unmounted") {
|
||||
if (state.type === "held") return cancelHold(state, [])
|
||||
|
||||
return state.type === "sending" ? settle(state, true, []) : unchanged(state)
|
||||
}
|
||||
|
||||
if (event.type === "gate.settled") {
|
||||
if (current(state, "sending", event.attempt)) return settle(state, true, [])
|
||||
|
||||
if (
|
||||
(current(state, "handing-off", event.attempt) || current(state, "running", event.attempt)) &&
|
||||
state.gate === "pending"
|
||||
)
|
||||
return { state: { ...state, gate: "settled" }, effects: [] }
|
||||
|
||||
// A result for a send that was cancelled, or that another one has replaced.
|
||||
return unchanged(state)
|
||||
}
|
||||
|
||||
// Only a prompt still in the composer cancels on an edit; a shown one left it, so the composer holds a new draft.
|
||||
if (event.type === "hold.changed")
|
||||
|
|
@ -257,9 +298,11 @@ export function transitionComposerSubmit(
|
|||
if (event.type === "session.started") {
|
||||
if (!current(state, "preparing", event.attempt)) return unchanged(state)
|
||||
const value = { ...state.value, images: event.images }
|
||||
// A shell command starts no step, so nothing prepares for it.
|
||||
const gate: SendGate = state.kind.type === "shell" ? "none" : "pending"
|
||||
|
||||
return {
|
||||
state: { ...state, type: "handing-off", value, session: event.session },
|
||||
state: { ...state, type: "handing-off", value, session: event.session, gate },
|
||||
effects: [
|
||||
// A shown hold recorded it when it left the composer.
|
||||
...(state.cleared ? [] : [{ type: "history.record" as const, prompt: value.prompt, mode: value.mode }]),
|
||||
|
|
@ -269,6 +312,7 @@ export function transitionComposerSubmit(
|
|||
session: event.session,
|
||||
value,
|
||||
sendFirst: state.kind.type === "prompt",
|
||||
gated: gate === "pending",
|
||||
ready: event.ready,
|
||||
complete: event.complete,
|
||||
},
|
||||
|
|
@ -297,24 +341,32 @@ export function transitionComposerSubmit(
|
|||
|
||||
if (!current(state, "handing-off", event.attempt)) return unchanged(state)
|
||||
|
||||
return settle(state, true, [
|
||||
{
|
||||
type: "composer.clear",
|
||||
draft: state.draft,
|
||||
value: state.value,
|
||||
kind: state.kind,
|
||||
comments: state.comments,
|
||||
session: state.session,
|
||||
prompt: event.prompt,
|
||||
cleared: state.cleared,
|
||||
},
|
||||
])
|
||||
const clear: ComposerSubmitEffect = {
|
||||
type: "composer.clear",
|
||||
attempt: state.attempt,
|
||||
draft: state.draft,
|
||||
value: state.value,
|
||||
kind: state.kind,
|
||||
comments: state.comments,
|
||||
session: state.session,
|
||||
prompt: event.prompt,
|
||||
cleared: state.cleared,
|
||||
}
|
||||
|
||||
// The composer clears now, as the send already shows in its Session. Its request has not left yet, so the composer
|
||||
// waits with it rather than taking the next send.
|
||||
if (state.gate === "pending")
|
||||
return { state: { type: "sending", attempt: state.attempt, done: state.done }, effects: [clear] }
|
||||
|
||||
return settle(state, true, [clear])
|
||||
}
|
||||
|
||||
export function composerSubmitView(state: ComposerSubmitState) {
|
||||
return {
|
||||
held: state.type === "held",
|
||||
busy: state.type === "held" || state.type === "preparing" || state.type === "handing-off",
|
||||
// Stop and Escape cancel the send rather than interrupt the Session.
|
||||
held: state.type === "held" || state.type === "sending",
|
||||
busy:
|
||||
state.type === "held" || state.type === "preparing" || state.type === "handing-off" || state.type === "sending",
|
||||
canSubmit: state.type === "idle",
|
||||
}
|
||||
}
|
||||
|
|
@ -324,13 +376,29 @@ export function composerSubmitTarget(state: ComposerSubmitState, attempt: number
|
|||
if (current(state, "preparing", attempt) || current(state, "handing-off", attempt)) return state.draft.target
|
||||
}
|
||||
|
||||
// Stop and Escape. A send whose request has not left yet is cancelled, and nothing of it reaches the server: a held
|
||||
// one, and one that waits on the gate. Otherwise they interrupt the Session, never both.
|
||||
function stop(state: ComposerSubmitState): ComposerSubmitTransition {
|
||||
if (state.type === "held") return cancelHold(state, [])
|
||||
|
||||
// The composer still has its draft, or gets it back from the send that fails as cancelled.
|
||||
if (state.type === "sending" || (state.type === "handing-off" && state.gate === "pending"))
|
||||
return settle(state, false, [{ type: "send.cancel", attempt: state.attempt }])
|
||||
|
||||
// The quote's own send settles the run once it fails as cancelled.
|
||||
if (state.type === "running" && state.gate === "pending")
|
||||
return { state, effects: [{ type: "send.cancel", attempt: state.attempt }] }
|
||||
|
||||
return { state, effects: [{ type: "interrupt" }] }
|
||||
}
|
||||
|
||||
function submit(state: ComposerSubmitState, snapshot: SubmitSnapshot, done: SubmitDone): ComposerSubmitTransition {
|
||||
if (state.type !== "idle") return { state, effects: [{ type: "done", done, sent: false }] }
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
if (snapshot.mode === "normal" && snapshot.clientCommand)
|
||||
return {
|
||||
state: { type: "running", attempt, done },
|
||||
state: { type: "running", attempt, gate: "none", done },
|
||||
effects: [{ type: "command.run", attempt, prompt: snapshot.draft.prompt, run: snapshot.clientCommand }],
|
||||
}
|
||||
|
||||
|
|
@ -427,7 +495,7 @@ function quote(state: ComposerSubmitState, snapshot: QuoteSnapshot, done: Submit
|
|||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { type: "running", attempt, done },
|
||||
state: { type: "running", attempt, gate: "pending", done },
|
||||
effects: [
|
||||
{
|
||||
type: "quote.send",
|
||||
|
|
|
|||
|
|
@ -314,6 +314,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
|||
return (alternate ? queue.alternate() : queue.delivery()) ?? "steer"
|
||||
},
|
||||
queueFirst: (inboxID) => options?.queue?.first(inboxID),
|
||||
ready: (sessionID) => plugins.ready(server.key, sessionID),
|
||||
notify: {
|
||||
missingSelection: () =>
|
||||
showToast({
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
import { describe, expect, jest, test } from "bun:test"
|
||||
import { afterEach, describe, expect, jest, test } from "bun:test"
|
||||
import type { SessionRef } from "@opencode/plugin/gui"
|
||||
import type { ModelSelection } from "@/providers/models/selection"
|
||||
import { PROMPT_GATE_TIMEOUT_MS, settlePromptGates } from "@/runtime/plugin/prompt-gate"
|
||||
import type { SessionMessageHandoff } from "@/session/handoff"
|
||||
import { Skill } from "@opencode/schema/skill"
|
||||
import { createRoot } from "solid-js"
|
||||
import type {
|
||||
ActiveComposerAdapter,
|
||||
ComposerControls,
|
||||
|
|
@ -86,9 +89,11 @@ function submitInput(
|
|||
history: string[] = [],
|
||||
clientCommand?: (text: string) => (() => void | Promise<void>) | undefined,
|
||||
delivery: (alternate: boolean) => ComposerDelivery = () => "steer",
|
||||
ready?: Parameters<typeof createComposerSubmit>[0]["ready"],
|
||||
) {
|
||||
return createComposerSubmit({
|
||||
adapter,
|
||||
ready,
|
||||
mode: () => mode,
|
||||
commands,
|
||||
clientCommand,
|
||||
|
|
@ -121,7 +126,27 @@ function session(input: {
|
|||
switchModel?: ComposerSession["api"]["switchModel"]
|
||||
background?: ComposerSession["background"]
|
||||
accept?: () => void
|
||||
/** Requests leave as the data layer's send chain lets them: each once the one before it has settled. */
|
||||
chained?: boolean
|
||||
}): ComposerSession {
|
||||
// The requests made so far, settled or not: the next one starts once they all have.
|
||||
const chain: Promise<unknown>[] = []
|
||||
|
||||
const sequence: ComposerSession["data"]["session"]["sequence"] = (_sessionID, send, prepare) => {
|
||||
const run = async () => {
|
||||
await prepare?.()
|
||||
|
||||
return send()
|
||||
}
|
||||
|
||||
if (!input.chained) return run()
|
||||
const next = Promise.all(chain.splice(0)).then(run)
|
||||
|
||||
chain.push(next.catch(() => undefined))
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
return {
|
||||
// Unique per test: what this client knows about a session outlives the test that sent to it.
|
||||
id: `session-${++sessions.count}`,
|
||||
|
|
@ -162,22 +187,26 @@ function session(input: {
|
|||
input.calls.push("accept-send")
|
||||
input.accept?.()
|
||||
},
|
||||
// Like the data layer: admit locally, prepare, then send.
|
||||
prompt: async (value) => {
|
||||
sequence,
|
||||
// Like the data layer: admit locally, then prepare and send in the session's send chain.
|
||||
prompt: (value) => {
|
||||
input.calls.push("admit")
|
||||
await value.prepare?.()
|
||||
input.calls.push("send")
|
||||
await input.prompt?.(value)
|
||||
|
||||
// The admitted inbox item, as the server returns it.
|
||||
return {
|
||||
id: value.id ?? "msg_admitted",
|
||||
sessionID: value.sessionID,
|
||||
time: { created: 0 },
|
||||
type: "user" as const,
|
||||
payload: { text: value.text },
|
||||
delivery: value.delivery ?? "steer",
|
||||
}
|
||||
return sequence(value.sessionID, async () => {
|
||||
await value.prepare?.()
|
||||
input.calls.push("send")
|
||||
await input.prompt?.(value)
|
||||
|
||||
// The admitted inbox item, as the server returns it.
|
||||
return {
|
||||
id: value.id ?? "msg_admitted",
|
||||
sessionID: value.sessionID,
|
||||
time: { created: 0 },
|
||||
type: "user" as const,
|
||||
payload: { text: value.text },
|
||||
delivery: value.delivery ?? "steer",
|
||||
}
|
||||
})
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
@ -213,6 +242,310 @@ describe("Composer submission", () => {
|
|||
expect(calls).toContain("admit")
|
||||
})
|
||||
|
||||
// Runs the promise jobs queued so far: more turns than a send's longest chain before its request leaves.
|
||||
const flush = async () => {
|
||||
for (const _ of Array.from({ length: 32 })) await Promise.resolve()
|
||||
}
|
||||
|
||||
const typed = (content: string): Prompt => [{ type: "text", content, start: 0, end: content.length }]
|
||||
|
||||
// A composer of `target` whose sends wait on `ready`, with what it reported as failed.
|
||||
const gated = (
|
||||
target: ComposerSession,
|
||||
ready: (sessionID: string) => Promise<void>,
|
||||
input: { prompt: string; mode?: "normal" | "shell"; calls?: string[] },
|
||||
) => {
|
||||
const state = createMemoryComposerState({ prompt: input.prompt }).capture()
|
||||
const failures: string[] = []
|
||||
const history: string[] = []
|
||||
const adapter = { ...active(state, target), interrupt: async () => void input.calls?.push("interrupt") }
|
||||
|
||||
const submission = submitInput(
|
||||
adapter,
|
||||
{ missingSelection() {}, unqueueable() {}, failed: (kind) => failures.push(kind) },
|
||||
input.mode ?? "normal",
|
||||
() => [{ name: "review" }],
|
||||
history,
|
||||
undefined,
|
||||
() => "steer",
|
||||
ready,
|
||||
)
|
||||
|
||||
return { state, submission, failures, history }
|
||||
}
|
||||
|
||||
test("a prompt shows at once, and its composer takes no other send until what the plugins prepare is ready", async () => {
|
||||
const calls: string[] = []
|
||||
const gate = Promise.withResolvers<void>()
|
||||
const sent = Promise.withResolvers<void>()
|
||||
const target = session({ calls, prompt: async () => sent.resolve() })
|
||||
|
||||
const composer = gated(
|
||||
target,
|
||||
(sessionID) => {
|
||||
calls.push(sessionID === target.id ? "gate" : "gate for another session")
|
||||
|
||||
return gate.promise
|
||||
},
|
||||
{ prompt: "Hello" },
|
||||
)
|
||||
|
||||
const submitted = composer.submission.submit(new Event("submit"))
|
||||
await flush()
|
||||
|
||||
// The prompt is admitted locally and the composer cleared, but nothing has left, and the send is still the
|
||||
// composer's: its view offers Stop for it.
|
||||
expect(calls.filter((call) => call === "gate" || call === "admit" || call === "send")).toEqual(["gate", "admit"])
|
||||
expect(text(composer.state)).toBe("")
|
||||
expect(composer.submission.state().type).toBe("sending")
|
||||
|
||||
// A second Enter, on whatever was typed meanwhile, starts no second send.
|
||||
composer.state.set(typed("again"), 5)
|
||||
await composer.submission.submit(new Event("submit"))
|
||||
expect(calls.filter((call) => call === "gate" || call === "admit")).toEqual(["gate", "admit"])
|
||||
expect(text(composer.state)).toBe("again")
|
||||
|
||||
gate.resolve()
|
||||
await submitted
|
||||
await sent.promise
|
||||
expect(calls.filter((call) => call === "gate" || call === "admit" || call === "send")).toEqual(["gate", "admit", "send"])
|
||||
expect(composer.submission.state()).toEqual({ type: "idle", attempt: 1 })
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ name: "a prompt", prompt: "Hello", left: "Hello" },
|
||||
{ name: "a prompt, with a draft typed since", prompt: "Hello", edit: "next", left: "Hello\n\nnext" },
|
||||
{ name: "a server command", prompt: "/review now", left: "/review now" },
|
||||
])("Stop while $name waits on the gate cancels that send: nothing reaches the server and its text comes back", async (row) => {
|
||||
const calls: string[] = []
|
||||
const timeline: string[] = []
|
||||
const statuses: ("idle" | "running")[] = []
|
||||
const gate = Promise.withResolvers<void>()
|
||||
|
||||
const target = session({
|
||||
calls,
|
||||
statuses,
|
||||
handoff: { set: () => timeline.push("set"), hold() {}, settle: () => timeline.push("settle"), clear: () => timeline.push("clear") },
|
||||
command: async () => void calls.push("command"),
|
||||
})
|
||||
|
||||
const composer = gated(target, () => gate.promise, { prompt: row.prompt, calls })
|
||||
const submitted = composer.submission.submit(new Event("submit"))
|
||||
await flush()
|
||||
expect(composer.submission.state().type).toBe("sending")
|
||||
expect(text(composer.state)).toBe("")
|
||||
|
||||
if (row.edit) composer.state.set(typed(row.edit), row.edit.length)
|
||||
await composer.submission.stop()
|
||||
await submitted
|
||||
await flush()
|
||||
|
||||
// Neither the request nor an interrupt: the Session was never told of this send.
|
||||
expect(calls.filter((call) => call === "send" || call === "command" || call === "interrupt")).toEqual([])
|
||||
expect(text(composer.state)).toBe(row.left)
|
||||
expect(composer.failures).toEqual([])
|
||||
expect(composer.submission.state()).toEqual({ type: "idle", attempt: 1 })
|
||||
// A prompt that showed in the Session is taken out of it again, and the Session is not left looking busy.
|
||||
expect(timeline).toEqual(row.prompt.startsWith("/") ? [] : ["set", "clear"])
|
||||
expect(statuses.at(-1) ?? "idle").toBe("idle")
|
||||
expect(composer.history).toEqual([`add:${row.prompt}`, `remove:${row.prompt}`])
|
||||
|
||||
// What the send waited for is ready later: the result belongs to a send that no longer exists.
|
||||
gate.resolve()
|
||||
await flush()
|
||||
expect(calls.filter((call) => call === "send" || call === "command")).toEqual([])
|
||||
expect(composer.submission.state()).toEqual({ type: "idle", attempt: 1 })
|
||||
})
|
||||
|
||||
test.each([
|
||||
{
|
||||
name: "a prompt into a staged revert, with another agent and model selected",
|
||||
prompt: "Hello",
|
||||
current: { agent: "plan", model: { id: "old", providerID: "old" }, revert: { messageID: "msg_reverted" } },
|
||||
},
|
||||
{
|
||||
name: "a prompt with another agent and model selected",
|
||||
prompt: "Hello",
|
||||
current: { agent: "plan", model: { id: "old", providerID: "old" } },
|
||||
},
|
||||
{
|
||||
name: "a server command with another agent and model selected",
|
||||
prompt: "/review now",
|
||||
current: { agent: "plan", model: { id: "old", providerID: "old" } },
|
||||
},
|
||||
])("Stop while $name waits on the gate changes nothing on the server", async (row) => {
|
||||
const calls: string[] = []
|
||||
const gate = Promise.withResolvers<void>()
|
||||
const target = session({ calls, current: () => row.current, command: async () => void calls.push("command") })
|
||||
const composer = gated(target, () => gate.promise, { prompt: row.prompt, calls })
|
||||
const submitted = composer.submission.submit(new Event("submit"))
|
||||
|
||||
await flush()
|
||||
await composer.submission.stop()
|
||||
await submitted
|
||||
gate.resolve()
|
||||
await flush()
|
||||
|
||||
// Only the prompt's local admission, which the cancelled send takes back: no revert commit, switch or request.
|
||||
expect(calls.filter((call) => call !== "admit")).toEqual([])
|
||||
expect(text(composer.state)).toBe(row.prompt)
|
||||
})
|
||||
|
||||
test("Stop while a prompt waits on the gate keeps a comment added meanwhile, though no text was typed", async () => {
|
||||
const gate = Promise.withResolvers<void>()
|
||||
const composer = gated(session({ calls: [] }), () => gate.promise, { prompt: "Hello" })
|
||||
composer.state.context.add({ type: "file", path: "src/sent.ts", comment: "Sent with it", commentID: "sent" })
|
||||
const submitted = composer.submission.submit(new Event("submit"))
|
||||
|
||||
await flush()
|
||||
expect(composer.state.context.items()).toEqual([])
|
||||
composer.state.context.add({ type: "file", path: "src/later.ts", comment: "Added while it waited", commentID: "later" })
|
||||
await composer.submission.stop()
|
||||
await submitted
|
||||
await flush()
|
||||
|
||||
expect(text(composer.state)).toBe("Hello")
|
||||
expect(composer.state.context.items().map((item) => item.type === "file" && item.comment)).toEqual([
|
||||
"Sent with it",
|
||||
"Added while it waited",
|
||||
])
|
||||
})
|
||||
|
||||
// The composer the person presses Stop in is not always the one that made the send: a new session's composer
|
||||
// unmounts as soon as Enter is pressed, and a tab switch away and back mounts a session's composer anew.
|
||||
test.each([
|
||||
{ name: "a new session's first prompt, from the session's own composer", draft: true },
|
||||
{ name: "a prompt whose composer a tab switch has replaced", draft: false },
|
||||
])("Stop cancels $name while it waits on the gate", async (row) => {
|
||||
const calls: string[] = []
|
||||
const timeline: string[] = []
|
||||
const failures: string[] = []
|
||||
const gate = Promise.withResolvers<void>()
|
||||
// The send ends one way or the other: its prompt leaves the timeline, or its request leaves the window.
|
||||
const ended = Promise.withResolvers<void>()
|
||||
|
||||
const target = session({
|
||||
calls,
|
||||
prompt: async () => ended.resolve(),
|
||||
handoff: {
|
||||
set: () => timeline.push("set"),
|
||||
hold() {},
|
||||
settle() {},
|
||||
clear: () => {
|
||||
timeline.push("clear")
|
||||
ended.resolve()
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const image = {
|
||||
type: "image" as const,
|
||||
id: "attachment",
|
||||
filename: "shot.png",
|
||||
mime: "image/png",
|
||||
blob: { id: "attachment", url: "data:image/png;base64,YQ==" },
|
||||
}
|
||||
|
||||
const draft = createMemoryComposerState({ prompt: "first prompt" }).capture()
|
||||
draft.set([...draft.current(), image])
|
||||
// What the session's composer holds: its own draft, which a new session's first prompt is moved to.
|
||||
const seen = row.draft ? createMemoryComposerState().capture() : draft
|
||||
|
||||
const sender = row.draft
|
||||
? fresh(draft, async (_selection, submission) => {
|
||||
submission.retarget(seen)
|
||||
|
||||
return { session: target, cleanupReady: Promise.resolve() }
|
||||
})
|
||||
: active(draft, target)
|
||||
|
||||
const notify = { missingSelection() {}, unqueueable() {}, failed: (kind: string) => void failures.push(kind) }
|
||||
|
||||
const compose = (adapter: ActiveComposerAdapter | NewSessionComposerAdapter) =>
|
||||
submitInput(adapter, notify, undefined, undefined, undefined, undefined, undefined, () => gate.promise)
|
||||
|
||||
const unmount = createRoot((dispose) => {
|
||||
void compose(sender).submit(new Event("submit"))
|
||||
|
||||
return dispose
|
||||
})
|
||||
|
||||
// A new session's composer goes at Enter; a tab switch comes once the prompt shows and waits.
|
||||
if (row.draft) unmount()
|
||||
await flush()
|
||||
|
||||
if (!row.draft) unmount()
|
||||
expect(timeline).toEqual(["set"])
|
||||
expect(text(seen)).toBe("")
|
||||
|
||||
await compose({ ...active(seen, target), interrupt: async () => void calls.push("interrupt") }).stop()
|
||||
// What the send waited for is ready later: the cancelled prompt must not leave then either.
|
||||
gate.resolve()
|
||||
await ended.promise
|
||||
await flush()
|
||||
|
||||
expect(calls.filter((call) => call === "send" || call === "interrupt")).toEqual([])
|
||||
expect(timeline).toEqual(["set", "clear"])
|
||||
expect(text(seen)).toBe("first prompt")
|
||||
expect(seen.current()).toContainEqual(image)
|
||||
expect(failures).toEqual([])
|
||||
|
||||
// Nothing waits any more, so the next Stop interrupts the session as before.
|
||||
await compose({ ...active(seen, target), interrupt: async () => void calls.push("interrupt") }).stop()
|
||||
expect(calls.filter((call) => call === "interrupt")).toEqual(["interrupt"])
|
||||
})
|
||||
|
||||
// A session's draft composer and its own composer are two of these. Each press of Enter is one send, and the server
|
||||
// must receive them in that order, whatever each waited for: here the prompt waits on the gate, the server command
|
||||
// on the gate and on the prompt, and the shell command, which has no gate, on both.
|
||||
describe("order", () => {
|
||||
afterEach(() => void jest.useRealTimers())
|
||||
|
||||
test.each(["is ready", "times out"] as const)(
|
||||
"a prompt, a server command and a shell command reach the server in that order when the gate %s",
|
||||
async (how) => {
|
||||
if (how === "times out") jest.useFakeTimers()
|
||||
const calls: string[] = []
|
||||
const gate = Promise.withResolvers<void>()
|
||||
|
||||
const target = session({
|
||||
calls,
|
||||
chained: true,
|
||||
prompt: async () => void calls.push("prompt"),
|
||||
command: async () => void calls.push("command"),
|
||||
shell: async () => void calls.push("shell"),
|
||||
})
|
||||
|
||||
// SAFETY: the gate under test never reads the session.
|
||||
const ref = { key: `server\n${target.id}`, id: target.id } as SessionRef
|
||||
const never = { plugin: "browser", value: { ready: () => new Promise<void>(() => undefined) } }
|
||||
|
||||
const ready = () =>
|
||||
how === "times out" ? settlePromptGates([never], () => true, ref) : gate.promise
|
||||
|
||||
const sends = [
|
||||
gated(target, ready, { prompt: "Hello" }),
|
||||
gated(target, ready, { prompt: "/review now" }),
|
||||
gated(target, ready, { prompt: "ls", mode: "shell" }),
|
||||
].map((composer) => composer.submission.submit(new Event("submit")))
|
||||
|
||||
await flush()
|
||||
// The shell command has nothing to wait for of its own, and still does not go first.
|
||||
expect(calls.filter((call) => call === "prompt" || call === "command" || call === "shell")).toEqual([])
|
||||
|
||||
if (how === "times out") jest.advanceTimersByTime(PROMPT_GATE_TIMEOUT_MS)
|
||||
gate.resolve()
|
||||
await Promise.all(sends)
|
||||
await flush()
|
||||
expect(calls.filter((call) => call === "prompt" || call === "command" || call === "shell")).toEqual([
|
||||
"prompt",
|
||||
"command",
|
||||
"shell",
|
||||
])
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("marks the session accepted only once the send is admitted", async () => {
|
||||
const calls: string[] = []
|
||||
const accepted = Promise.withResolvers<void>()
|
||||
|
|
|
|||
|
|
@ -44,6 +44,48 @@ const switched = new Map<string, string>()
|
|||
// the follow-ups sent from its own composer go through different submit machines. A session left out is `server`.
|
||||
const statuses = new Map<string, PromptStatusState>()
|
||||
|
||||
// Each session's last send, until it has joined the data layer's send chain. A send first builds its request
|
||||
// (attachments read, mentions checked), which takes one longer than another, and must still join after the sends made
|
||||
// before it. Module-wide for the same reason as `statuses`.
|
||||
const joining = new Map<string, Promise<void>>()
|
||||
|
||||
/** A send's place in its session's order: `before` is the send made before it, until that one has joined the chain. */
|
||||
type Turn = { before: Promise<void> | undefined; joined: () => void }
|
||||
|
||||
/**
|
||||
* Runs one send in its session's order. Call it before the first await. `send` builds its request in whatever time
|
||||
* that takes, waits for `before`, puts the request in the data layer's send chain and calls `joined` at once. A send
|
||||
* that ends without joining does not hold the next one back.
|
||||
*/
|
||||
function inTurn<T>(sessionID: string, send: (turn: Turn) => Promise<T>) {
|
||||
const mine = Promise.withResolvers<void>()
|
||||
const turn = { before: joining.get(sessionID), joined: () => mine.resolve() }
|
||||
|
||||
joining.set(sessionID, mine.promise)
|
||||
void mine.promise.then(() => {
|
||||
if (joining.get(sessionID) === mine.promise) joining.delete(sessionID)
|
||||
})
|
||||
const sending = send(turn)
|
||||
|
||||
void sending.then(turn.joined, turn.joined)
|
||||
|
||||
return sending
|
||||
}
|
||||
|
||||
/** What a cancelled send fails with: Stop pressed while its request still waited on the gate. */
|
||||
const CANCELLED = new Error("The send was cancelled before its request left.")
|
||||
|
||||
/**
|
||||
* A send's gate. `open` settles once its request may leave, and rejects with `CANCELLED` when `cancel` is called
|
||||
* first.
|
||||
*/
|
||||
type Gate = { open: Promise<void>; cancel: () => void }
|
||||
|
||||
// The gates each session's sends still wait on, by session ID, until each settles. Module-wide for the same reason as
|
||||
// `statuses`: a new session's composer unmounts while its first prompt waits, and a tab switch remounts a session's
|
||||
// composer, so the composer the person presses Stop in is not always the one that made the send.
|
||||
const waiting = new Map<string, Set<Gate>>()
|
||||
|
||||
type ComposerSubmitInput = {
|
||||
adapter: ComposerAdapter
|
||||
mode: Accessor<"normal" | "shell">
|
||||
|
|
@ -57,6 +99,11 @@ type ComposerSubmitInput = {
|
|||
delivery?: (alternate: boolean) => ComposerDelivery
|
||||
queueFirst?: (inboxID: string) => void
|
||||
clientCommand?: (text: string) => (() => void | Promise<void>) | undefined
|
||||
/**
|
||||
* What a prompt or a server command waits for before its request goes out: whatever the plugins prepare for the
|
||||
* session's next step. It never rejects and is bounded by the plugin host.
|
||||
*/
|
||||
ready?: (sessionID: string) => Promise<void>
|
||||
notify: {
|
||||
missingSelection: () => void
|
||||
unqueueable: () => void
|
||||
|
|
@ -80,15 +127,70 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
|
|||
result.effects.forEach(run)
|
||||
}
|
||||
|
||||
// The gate of each send that still waits on it, by attempt.
|
||||
const gates = new Map<number, Gate>()
|
||||
|
||||
// Starts what the send of `attempt` waits for, and tells the machine when it is ready. A send cancelled meanwhile
|
||||
// fails as `CANCELLED` and its late result is one the machine ignores.
|
||||
const openGate = (attempt: number, session: ComposerSession): Gate => {
|
||||
const ready = input.ready?.(session.id)
|
||||
const cancelled = Promise.withResolvers<never>()
|
||||
|
||||
// Nothing may be waiting on it when it is cancelled.
|
||||
void cancelled.promise.catch(() => undefined)
|
||||
|
||||
const gate = {
|
||||
open: ready ? Promise.race([ready, cancelled.promise]) : Promise.resolve(),
|
||||
cancel: () => cancelled.reject(CANCELLED),
|
||||
}
|
||||
|
||||
const settled = () => {
|
||||
if (gates.get(attempt) === gate) gates.delete(attempt)
|
||||
dispatch({ type: "gate.settled", attempt })
|
||||
}
|
||||
|
||||
gates.set(attempt, gate)
|
||||
|
||||
if (ready) {
|
||||
const pending = waiting.get(session.id) ?? new Set<Gate>()
|
||||
|
||||
waiting.set(session.id, pending.add(gate))
|
||||
void gate.open
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
pending.delete(gate)
|
||||
|
||||
if (pending.size === 0 && waiting.get(session.id) === pending) waiting.delete(session.id)
|
||||
})
|
||||
void ready.then(settled)
|
||||
} else settled()
|
||||
|
||||
return gate
|
||||
}
|
||||
|
||||
const run = (effect: ComposerSubmitEffect) => {
|
||||
if (effect.type === "done") return effect.done(effect.sent)
|
||||
|
||||
if (effect.type === "send.cancel") {
|
||||
const gate = gates.get(effect.attempt)
|
||||
|
||||
gates.delete(effect.attempt)
|
||||
|
||||
return gate?.cancel()
|
||||
}
|
||||
|
||||
if (effect.type === "notify.missing-selection") return input.notify.missingSelection()
|
||||
|
||||
if (effect.type === "notify.unqueueable") return input.notify.unqueueable()
|
||||
|
||||
if (effect.type === "interrupt") {
|
||||
if (input.adapter.kind === "active-session") void input.adapter.interrupt()
|
||||
if (input.adapter.kind !== "active-session") return
|
||||
// A send to this session that another composer made still waits on its gate. Nothing of it has reached the
|
||||
// server, so Stop cancels it, as this composer's own machine does for its own send, and interrupts nothing.
|
||||
const pending = waiting.get(input.adapter.session().id)
|
||||
|
||||
if (pending?.size) return pending.forEach((gate) => gate.cancel())
|
||||
void input.adapter.interrupt()
|
||||
|
||||
return
|
||||
}
|
||||
|
|
@ -146,7 +248,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
|
|||
input.adapter.beforeSubmit?.()
|
||||
const target = input.adapter.state
|
||||
|
||||
void dispatchPrompt(input, effect.session, effect.value)
|
||||
void dispatchPrompt(input, effect.session, effect.value, openGate(effect.attempt, effect.session))
|
||||
.settled(() => {
|
||||
target.context.updateComment(effect.quote.commentID, { comment: effect.comment })
|
||||
|
||||
|
|
@ -215,7 +317,8 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
|
|||
}
|
||||
|
||||
if (effect.type === "handoff") {
|
||||
const prompt = effect.sendFirst ? dispatchPrompt(input, effect.session, effect.value) : undefined
|
||||
const gate = effect.gated ? openGate(effect.attempt, effect.session) : undefined
|
||||
const prompt = effect.sendFirst ? dispatchPrompt(input, effect.session, effect.value, gate) : undefined
|
||||
|
||||
void effect.ready
|
||||
.then(() => effect.complete?.())
|
||||
|
|
@ -230,7 +333,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
|
|||
return
|
||||
}
|
||||
|
||||
clearSubmission(input, effect)
|
||||
clearSubmission(input, effect, gates.get(effect.attempt))
|
||||
}
|
||||
|
||||
// A held send goes through once the Location's agents and models load. One still in the composer ends if the draft
|
||||
|
|
@ -385,15 +488,23 @@ async function startSession(
|
|||
function clearSubmission(
|
||||
input: ComposerSubmitInput,
|
||||
effect: Extract<ComposerSubmitEffect, { type: "composer.clear" }>,
|
||||
gate: Gate | undefined,
|
||||
) {
|
||||
const held = effect.cleared
|
||||
const clear = held ? undefined : clearComposer(input, effect.draft, effect.kind.type)
|
||||
|
||||
// A held prompt cleared the composer at Enter, so what it goes back to is read only once the send fails.
|
||||
const restore = () => {
|
||||
const back = clear ?? (held && afterHold(effect.draft, held))
|
||||
// A held prompt cleared the composer at Enter, so what it goes back to is read only once the send fails. A
|
||||
// cancelled send comes back as a cancelled hold does: in front of a draft typed since, not dropped for it.
|
||||
const restore = (cancelled: boolean) => {
|
||||
const cleared = cancelled ? (clear?.cleared ?? held) : held
|
||||
const back = cleared ? afterHold(effect.draft, cleared) : clear
|
||||
|
||||
return !!back && restoreSubmission(input, effect, back)
|
||||
if (!back) return false
|
||||
|
||||
// A cancelled send loses nothing: a comment added while it waited stays, though no text was typed with it.
|
||||
const kept = cancelled && effect.draft.target.context.items().some(isCommentItem)
|
||||
|
||||
return restoreSubmission(input, effect, kept ? { ...back, edited: true } : back)
|
||||
}
|
||||
|
||||
if (effect.prompt) return void effect.prompt.settled(restore)
|
||||
|
|
@ -409,6 +520,7 @@ function clearSubmission(
|
|||
effect.value,
|
||||
effect.kind.command,
|
||||
input.adapter.controls().model.selection.trackSessionCommit,
|
||||
gate,
|
||||
).catch((error) => failSubmission(input, effect.session, "command", error, restore, effect.value.id))
|
||||
}
|
||||
|
||||
|
|
@ -532,7 +644,12 @@ function currentSelection(input: ComposerSubmitInput): ComposerSelection | undef
|
|||
}
|
||||
}
|
||||
|
||||
function dispatchPrompt(input: ComposerSubmitInput, session: ComposerSession, value: ComposerSubmission): PromptSend {
|
||||
function dispatchPrompt(
|
||||
input: ComposerSubmitInput,
|
||||
session: ComposerSession,
|
||||
value: ComposerSubmission,
|
||||
gate: Gate | undefined,
|
||||
): PromptSend {
|
||||
// A steer appears in the timeline before the composer clears; queued prompts appear in the queue on admission.
|
||||
if (value.delivery === "steer")
|
||||
session.handoff.set({
|
||||
|
|
@ -552,7 +669,7 @@ function dispatchPrompt(input: ComposerSubmitInput, session: ComposerSession, va
|
|||
|
||||
updateStatus(session, { type: "dispatched", id: value.id, working })
|
||||
|
||||
const sending = sendPrompt(session, value, input.adapter.controls().model.selection.trackSessionCommit).then(
|
||||
const sending = sendPrompt(session, value, input.adapter.controls().model.selection.trackSessionCommit, gate).then(
|
||||
() => ({ ok: true as const }),
|
||||
(error) => ({ ok: false as const, error }),
|
||||
)
|
||||
|
|
@ -705,35 +822,64 @@ function restoreDraft(
|
|||
return true
|
||||
}
|
||||
|
||||
async function sendShell(session: ComposerSession, value: ComposerSubmission) {
|
||||
await session.api.shell({ sessionID: session.id, id: value.id, command: value.text })
|
||||
// A shell command, a server command and a prompt all leave through the session's one send chain, each in its turn, so
|
||||
// the server receives them in the order of the Enter presses, whatever each had to build or wait for first.
|
||||
function sendShell(session: ComposerSession, value: ComposerSubmission) {
|
||||
return inTurn(session.id, async (turn) => {
|
||||
if (turn.before) await turn.before
|
||||
|
||||
const sending = session.data.session.sequence(session.id, () =>
|
||||
session.api.shell({ sessionID: session.id, id: value.id, command: value.text }),
|
||||
)
|
||||
|
||||
turn.joined()
|
||||
await sending
|
||||
})
|
||||
}
|
||||
|
||||
async function sendCommand(
|
||||
function sendCommand(
|
||||
session: ComposerSession,
|
||||
value: ComposerSubmission,
|
||||
command: { command: string; arguments: string },
|
||||
track?: ModelSelection["trackSessionCommit"],
|
||||
track: ModelSelection["trackSessionCommit"] | undefined,
|
||||
gate: Gate | undefined,
|
||||
) {
|
||||
const request = await buildSubmissionRequest(session, value)
|
||||
return inTurn(session.id, async (turn) => {
|
||||
const request = await buildSubmissionRequest(session, value)
|
||||
|
||||
// Like queued prompts, queued commands must not apply the composer's selection to active work.
|
||||
if (value.delivery === "steer") await applySelection(session, value.selection, track)
|
||||
await session.api.command({
|
||||
sessionID: session.id,
|
||||
name: command.command,
|
||||
text: command.arguments,
|
||||
files: request.files.map((file) => ({
|
||||
uri: file.uri,
|
||||
name: file.name,
|
||||
description: file.description,
|
||||
mention: file.mention,
|
||||
})),
|
||||
agents: request.agents,
|
||||
skills: request.skills,
|
||||
delivery: value.delivery,
|
||||
if (turn.before) await turn.before
|
||||
|
||||
const sending = session.data.session.sequence(
|
||||
session.id,
|
||||
() =>
|
||||
session.api.command({
|
||||
sessionID: session.id,
|
||||
name: command.command,
|
||||
text: command.arguments,
|
||||
files: request.files.map((file) => ({
|
||||
uri: file.uri,
|
||||
name: file.name,
|
||||
description: file.description,
|
||||
mention: file.mention,
|
||||
})),
|
||||
agents: request.agents,
|
||||
skills: request.skills,
|
||||
delivery: value.delivery,
|
||||
}),
|
||||
// What the request waits for is not part of its place in the chain's order. A send cancelled while it waits on
|
||||
// the gate stops there, before the composer's selection is committed: nothing of it reaches the server.
|
||||
async () => {
|
||||
await gate?.open
|
||||
|
||||
// Like queued prompts, queued commands must not apply the composer's selection to active work.
|
||||
if (value.delivery === "steer") await applySelection(session, value.selection, track)
|
||||
},
|
||||
)
|
||||
|
||||
turn.joined()
|
||||
await sending
|
||||
session.data.session.acceptSend(session.id)
|
||||
})
|
||||
session.data.session.acceptSend(session.id)
|
||||
}
|
||||
|
||||
async function applySelection(
|
||||
|
|
@ -776,10 +922,21 @@ async function applySelection(
|
|||
}
|
||||
}
|
||||
|
||||
async function sendPrompt(
|
||||
function sendPrompt(
|
||||
session: ComposerSession,
|
||||
value: ComposerSubmission,
|
||||
track: ModelSelection["trackSessionCommit"] | undefined,
|
||||
gate: Gate | undefined,
|
||||
) {
|
||||
return inTurn(session.id, (turn) => admitPrompt(session, value, track, gate, turn))
|
||||
}
|
||||
|
||||
async function admitPrompt(
|
||||
session: ComposerSession,
|
||||
value: ComposerSubmission,
|
||||
track: ModelSelection["trackSessionCommit"] | undefined,
|
||||
gate: Gate | undefined,
|
||||
turn: Turn,
|
||||
) {
|
||||
const request = await buildSubmissionRequest(session, value)
|
||||
|
||||
|
|
@ -801,9 +958,15 @@ async function sendPrompt(
|
|||
// pending.
|
||||
const staged = !!session.current()?.revert
|
||||
|
||||
if (staged) await commit()
|
||||
// A send cancelled while it waits on the gate stops before anything of it reaches the server: the staged revert
|
||||
// stays staged, and the agent and model stay as they were.
|
||||
if (staged) {
|
||||
await gate?.open
|
||||
await commit()
|
||||
}
|
||||
|
||||
// A retried admission reuses the first commit rather than switching again.
|
||||
let committed: Promise<void> | undefined
|
||||
let committed: Promise<unknown> | undefined
|
||||
|
||||
const admission = {
|
||||
id: value.id,
|
||||
|
|
@ -825,10 +988,17 @@ async function sendPrompt(
|
|||
agent: value.selection.agent,
|
||||
model: selectionModel(value.selection),
|
||||
},
|
||||
prepare: staged ? undefined : () => (committed ??= commit()),
|
||||
// The data layer runs this in the prompt's turn of the send chain. The selection's commit follows what the
|
||||
// plugins prepare, so a send cancelled meanwhile stops here and nothing of it reaches the server.
|
||||
prepare: () => (committed ??= (gate?.open ?? Promise.resolve()).then(() => (staged ? undefined : commit()))),
|
||||
}
|
||||
|
||||
await session.data.session.prompt(admission).catch(() => session.data.session.prompt(admission))
|
||||
if (turn.before) await turn.before
|
||||
const sending = session.data.session.prompt(admission)
|
||||
|
||||
turn.joined()
|
||||
// An admission that fails is tried once more. A cancelled one is not: the person stopped it.
|
||||
await sending.catch((error) => (error === CANCELLED ? Promise.reject(error) : session.data.session.prompt(admission)))
|
||||
session.data.session.acceptSend(session.id)
|
||||
}
|
||||
|
||||
|
|
@ -880,12 +1050,14 @@ function failSubmission(
|
|||
kind: "shell" | "command" | "prompt",
|
||||
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- a rejected send is opaque; the notifier formats it
|
||||
error: unknown,
|
||||
restore: () => boolean,
|
||||
restore: (cancelled: boolean) => boolean,
|
||||
messageID?: string,
|
||||
) {
|
||||
if (messageID && session.admitted(messageID)) return true
|
||||
restore()
|
||||
input.notify.failed(kind, error)
|
||||
restore(error === CANCELLED)
|
||||
|
||||
// A cancelled send is what the person asked for, not a failure to report.
|
||||
if (error !== CANCELLED) input.notify.failed(kind, error)
|
||||
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -232,7 +232,8 @@ function locale(value: string) {
|
|||
const normalizeScript = (script?: string) => (script === "Aran" ? "Arab" : script)
|
||||
|
||||
export const DESKTOP_NATIVE_ENGLISH = {
|
||||
"desktop.microphoneUsage": "OpenCode uses your microphone for voice calls.",
|
||||
"desktop.microphoneUsage": "OpenCode uses your microphone for voice calls and lets websites you allow in the browser pane use it.",
|
||||
"desktop.cameraUsage": "OpenCode lets websites you allow in the browser pane use your camera.",
|
||||
"desktop.documentsFolderUsage":
|
||||
"OpenCode uses files in your Documents folder for projects you open and commands you run there.",
|
||||
"desktop.desktopFolderUsage": "OpenCode uses files on your Desktop for projects you open and commands you run there.",
|
||||
|
|
|
|||
|
|
@ -48,9 +48,6 @@ type PlatformBase = {
|
|||
/** Open a local path in a local app (desktop only) */
|
||||
openPath?(path: string, app?: string): Promise<void>
|
||||
|
||||
/** Open a local file URL in its default app (desktop only) */
|
||||
openLocalFile?(url: string): void
|
||||
|
||||
/** Reveal a local path in the system file manager; false when the path does not exist (desktop only) */
|
||||
revealPath?(path: string): Promise<boolean>
|
||||
|
||||
|
|
|
|||
17
packages/app/src/runtime/plugin/app-links.test.ts
Normal file
17
packages/app/src/runtime/plugin/app-links.test.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { appLinkRoute } from "./app-links"
|
||||
|
||||
// A mail address is the system mail app's with or without a reviewer; only an attachment parameter keeps it out.
|
||||
test.each([
|
||||
["mailto:hello@example.invalid", true, "mail"],
|
||||
["mailto:hello@example.invalid", false, "mail"],
|
||||
["MAILTO:hello@example.invalid?subject=Hi&body=There", false, "mail"],
|
||||
["mailto:hello@example.invalid?attach=C:/secrets.txt", true, "copy"],
|
||||
["mailto:hello@example.invalid?Attachment=/etc/passwd", false, "copy"],
|
||||
["tel:+15555550100", true, "review"],
|
||||
["tel:+15555550100", false, "copy"],
|
||||
["obsidian://open?vault=notes", true, "review"],
|
||||
["vscode://file/repo/index.ts", false, "copy"],
|
||||
] as const)("%s with a reviewer %s goes to %s", (href, reviewer, route) => {
|
||||
expect(appLinkRoute(href, reviewer)).toBe(route)
|
||||
})
|
||||
88
packages/app/src/runtime/plugin/app-links.ts
Normal file
88
packages/app/src/runtime/plugin/app-links.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
|
||||
function target(event: Event) {
|
||||
const anchor = event.target instanceof Element ? event.target.closest("a") : null
|
||||
|
||||
if (!(anchor instanceof HTMLAnchorElement) || !anchor.closest("[data-pane-row]")) return
|
||||
const href = anchor.dataset.appLink
|
||||
|
||||
if (!href || /^[a-z]:[\\/]/i.test(href)) return
|
||||
const protocol = URL.parse(href)?.protocol
|
||||
|
||||
if (!protocol || /^(https?|file):$/.test(protocol)) return
|
||||
|
||||
return { anchor, href }
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a click on another app's address goes. A mail address opens in the system mail app, as on dev, never in the
|
||||
* browser pane; one with an attachment parameter could make the mail app attach a local file, so it is only copied.
|
||||
* Any other address goes to the reviewer when one is installed, and is copied when none is.
|
||||
*/
|
||||
export function appLinkRoute(href: string, reviewer: boolean) {
|
||||
if (/^mailto:/i.test(href))
|
||||
return Array.from(URL.parse(href)?.searchParams.keys() ?? []).some((key) => /^(?:attach|attachment)$/i.test(key))
|
||||
? "copy"
|
||||
: "mail"
|
||||
|
||||
return reviewer ? "review" : "copy"
|
||||
}
|
||||
|
||||
function modified(event: MouseEvent | KeyboardEvent) {
|
||||
return event.metaKey || event.shiftKey || event.ctrlKey || event.altKey
|
||||
}
|
||||
|
||||
export function createAppLinks(review: (href: string) => void) {
|
||||
let pressed: ReturnType<typeof target>
|
||||
makeEventListener(
|
||||
document,
|
||||
"pointerdown",
|
||||
(event) => {
|
||||
pressed = event.isTrusted && event.button === 0 && !modified(event) ? target(event) : undefined
|
||||
},
|
||||
true,
|
||||
)
|
||||
makeEventListener(
|
||||
document,
|
||||
"pointercancel",
|
||||
() => {
|
||||
pressed = undefined
|
||||
},
|
||||
true,
|
||||
)
|
||||
makeEventListener(
|
||||
document,
|
||||
"keydown",
|
||||
(event) => {
|
||||
if (event.key !== "Enter") return
|
||||
const link = target(event)
|
||||
|
||||
if (!link) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
|
||||
if (event.isTrusted && !modified(event) && !event.repeat && link.anchor === document.activeElement) review(link.href)
|
||||
},
|
||||
true,
|
||||
)
|
||||
|
||||
const click = (event: MouseEvent) => {
|
||||
const start = pressed
|
||||
pressed = undefined
|
||||
const link = target(event)
|
||||
|
||||
if (!link) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
|
||||
// A stream can replace the anchor or change its target between press and release.
|
||||
if (event.type !== "click" || !event.isTrusted || modified(event) || event.button !== 0) return
|
||||
const paired = event.detail !== 0 && start?.anchor === link.anchor && start.href === link.href
|
||||
const assistive = !start && event.detail === 0 && link.anchor === document.activeElement
|
||||
|
||||
if (paired || assistive) review(link.href)
|
||||
}
|
||||
|
||||
makeEventListener(document, "click", click, true)
|
||||
makeEventListener(document, "auxclick", click, true)
|
||||
}
|
||||
18
packages/app/src/runtime/plugin/embed-geometry.test.ts
Normal file
18
packages/app/src/runtime/plugin/embed-geometry.test.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { embedBounds, overlaps } from "./embed-geometry"
|
||||
|
||||
test("rounds physical edges separately in window DIPs after layout has resolved direction", () => {
|
||||
expect(embedBounds({ left: 120.4, right: 220.8, top: 20.4, bottom: 30.4 }, 1.25)).toEqual({
|
||||
x: 151,
|
||||
y: 26,
|
||||
width: 125,
|
||||
height: 12,
|
||||
})
|
||||
})
|
||||
|
||||
test("only positive-area intersections cover a pane or put it on screen", () => {
|
||||
const pane = { left: 12, right: 44, top: 10, bottom: 50 }
|
||||
expect(overlaps(pane, { ...pane, left: 43 })).toBe(true)
|
||||
expect(overlaps(pane, { ...pane, left: 44, right: 99 })).toBe(false)
|
||||
expect(overlaps(pane, { ...pane, top: 22, bottom: 22 })).toBe(false)
|
||||
})
|
||||
19
packages/app/src/runtime/plugin/embed-geometry.ts
Normal file
19
packages/app/src/runtime/plugin/embed-geometry.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
type Edges = Pick<DOMRect, "left" | "top" | "right" | "bottom">
|
||||
|
||||
// Both DOMRect and Electron measure from the physical left, including in RTL. Electron wants DIPs, not screen pixels:
|
||||
// only the window's page zoom belongs in this conversion, not the monitor's device scale factor.
|
||||
export function embedBounds(rect: Edges, zoom: number) {
|
||||
const x = Math.round(rect.left * zoom)
|
||||
const y = Math.round(rect.top * zoom)
|
||||
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
width: Math.max(0, Math.round(rect.right * zoom) - x),
|
||||
height: Math.max(0, Math.round(rect.bottom * zoom) - y),
|
||||
}
|
||||
}
|
||||
|
||||
export function overlaps(a: Edges, b: Edges) {
|
||||
return Math.min(a.right, b.right) > Math.max(a.left, b.left) && Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top)
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import {
|
|||
selectSnapshotHidesNative,
|
||||
selectSnapshotNeedsSync,
|
||||
selectSnapshotUrl,
|
||||
selectSnapshotWantsStill,
|
||||
transitionEmbedSnapshot,
|
||||
type EmbedSnapshotEffect,
|
||||
type EmbedSnapshotEvent,
|
||||
|
|
@ -74,7 +75,7 @@ describe("bug replays", () => {
|
|||
expect(selectSnapshotHidesNative(next.state, "embed-Alpha", true)).toBe(true)
|
||||
})
|
||||
|
||||
test("a failed or corrupt capture hides the native view without a still and thaws at once", () => {
|
||||
test("a failed capture still gives the warm fallback a thaw interval", () => {
|
||||
const failed = transitionEmbedSnapshot(capturing, settled(1, undefined))
|
||||
expect(failed.state).toEqual({ status: "frozen", issued: 1, id: "embed-Alpha", url: undefined })
|
||||
expect(failed.effects).toEqual([{ type: "capture-timer.stop" }, { type: "layout.schedule" }])
|
||||
|
|
@ -82,8 +83,24 @@ describe("bug replays", () => {
|
|||
expect(selectSnapshotHidesNative(failed.state, "embed-Alpha", true)).toBe(true)
|
||||
|
||||
const uncovered = transitionEmbedSnapshot(failed.state, sync(false))
|
||||
expect(uncovered.state).toEqual({ status: "live", issued: 1 })
|
||||
expect(uncovered.effects).toEqual([])
|
||||
expect(uncovered.state).toMatchObject({ status: "thawing", url: undefined })
|
||||
expect(uncovered.effects).toEqual([{ type: "thaw-timer.start", delayMs: SNAPSHOT_THAW_DELAY_MS, attempt: 2 }])
|
||||
expect(selectSnapshotHidesNative(uncovered.state, "embed-Alpha", false)).toBe(false)
|
||||
|
||||
const live = transitionEmbedSnapshot(uncovered.state, { type: "thaw.settled", attempt: 2 })
|
||||
expect(live).toEqual({ state: { status: "live", issued: 2 }, effects: [{ type: "layout.schedule" }] })
|
||||
})
|
||||
|
||||
test("a warm still hides the native view only once the capture, which needs the view visible, has returned", () => {
|
||||
expect(selectSnapshotHidesNative(capturing, "embed-Alpha", true, true)).toBe(false)
|
||||
expect(selectSnapshotHidesNative(painting, "embed-Alpha", true, false)).toBe(false)
|
||||
expect(selectSnapshotHidesNative(painting, "embed-Alpha", true, true)).toBe(true)
|
||||
expect(selectSnapshotHidesNative(painting, "embed-Beta", true, true)).toBe(false)
|
||||
expect(selectSnapshotHidesNative(painting, "embed-Alpha", false, true)).toBe(false)
|
||||
// The warm still keeps covering through the thaw, when the cover itself has ended.
|
||||
expect(selectSnapshotWantsStill(thawing, "embed-Alpha", false)).toBe(true)
|
||||
expect(selectSnapshotWantsStill(INITIAL_SNAPSHOT_STATE, "embed-Alpha", false)).toBe(false)
|
||||
expect(selectSnapshotWantsStill(thawing, "embed-Beta", false)).toBe(false)
|
||||
})
|
||||
|
||||
test("another embed taking a covered box gives up the previous still in the same step", () => {
|
||||
|
|
@ -114,6 +131,7 @@ describe("lifecycle", () => {
|
|||
expect(decoded.effects).toEqual([
|
||||
{ type: "capture-timer.stop" },
|
||||
{ type: "paint-timer.start", attempt: 1, delayMs: SNAPSHOT_PAINT_TIMEOUT_MS },
|
||||
{ type: "layout.schedule" },
|
||||
])
|
||||
|
||||
const presented = transitionEmbedSnapshot(decoded.state, { type: "snapshot.painted", url: "blob:a" })
|
||||
|
|
@ -128,7 +146,7 @@ describe("lifecycle", () => {
|
|||
|
||||
const released = transitionEmbedSnapshot(uncovered.state, { type: "thaw.settled", attempt: 2 })
|
||||
expect(released.state).toEqual({ status: "live", issued: 2 })
|
||||
expect(released.effects).toEqual([{ type: "url.revoke", url: "blob:a" }])
|
||||
expect(released.effects).toEqual([{ type: "url.revoke", url: "blob:a" }, { type: "layout.schedule" }])
|
||||
})
|
||||
|
||||
test("covering again while thawing keeps the still and ignores the old thaw", () => {
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ export type EmbedSnapshotState =
|
|||
readonly issued: number
|
||||
readonly attempt: number
|
||||
readonly id: string
|
||||
readonly url: string
|
||||
readonly url: string | undefined
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
|
|
@ -85,6 +85,8 @@ const EMPTY_EFFECTS: readonly EmbedSnapshotEffect[] = Object.freeze([])
|
|||
|
||||
const LAYOUT: readonly EmbedSnapshotEffect[] = Object.freeze([{ type: "layout.schedule" }])
|
||||
|
||||
const THAW_STOP: readonly EmbedSnapshotEffect[] = Object.freeze([{ type: "thaw-timer.stop" }])
|
||||
|
||||
export function transitionEmbedSnapshot(state: EmbedSnapshotState, event: EmbedSnapshotEvent): EmbedSnapshotTransition {
|
||||
// A capture that settles after its attempt ended still owns its URL.
|
||||
if (event.type === "capture.settled" && (state.status !== "capturing" || state.attempt !== event.attempt))
|
||||
|
|
@ -101,9 +103,11 @@ export function transitionEmbedSnapshot(state: EmbedSnapshotState, event: EmbedS
|
|||
|
||||
return {
|
||||
state: { status: "painting", issued: state.issued, attempt: state.attempt, id: state.id, url: event.url },
|
||||
// Measure again: a warm still already on screen can take over from the native view now the capture is done.
|
||||
effects: [
|
||||
{ type: "capture-timer.stop" },
|
||||
{ type: "paint-timer.start", attempt: state.attempt, delayMs: SNAPSHOT_PAINT_TIMEOUT_MS },
|
||||
{ type: "layout.schedule" },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
|
@ -118,7 +122,11 @@ export function transitionEmbedSnapshot(state: EmbedSnapshotState, event: EmbedS
|
|||
return frozen(state, state.url, LAYOUT)
|
||||
|
||||
if (event.type === "thaw.settled" && state.status === "thawing" && state.attempt === event.attempt)
|
||||
return { state: { status: "live", issued: state.issued }, effects: [{ type: "url.revoke", url: state.url }] }
|
||||
return {
|
||||
state: { status: "live", issued: state.issued },
|
||||
// Measure again: a warm still that covered the thaw comes down with it.
|
||||
effects: state.url ? [{ type: "url.revoke", url: state.url }, { type: "layout.schedule" }] : LAYOUT,
|
||||
}
|
||||
|
||||
return unchanged(state)
|
||||
}
|
||||
|
|
@ -132,9 +140,19 @@ export function selectSnapshotUrl(state: EmbedSnapshotState, id: string | undefi
|
|||
return state.id === id ? state.url : undefined
|
||||
}
|
||||
|
||||
/** Whether the native view of `id` hides under the cover, because a frame has presented its still. */
|
||||
export function selectSnapshotHidesNative(state: EmbedSnapshotState, id: string | undefined, covered: boolean) {
|
||||
return covered && id !== undefined && state.status === "frozen" && state.id === id
|
||||
/**
|
||||
* Whether the native view of `id` hides under the cover: a frame has presented its still, or a warm still is already
|
||||
* on screen and the capture, which needs the view visible, has returned.
|
||||
*/
|
||||
export function selectSnapshotHidesNative(state: EmbedSnapshotState, id: string | undefined, covered: boolean, warm = false) {
|
||||
if (!covered || id === undefined || state.status === "live" || state.status === "disposed" || state.id !== id) return false
|
||||
|
||||
return state.status === "frozen" || (warm && state.status === "painting")
|
||||
}
|
||||
|
||||
/** Whether the box wants a still under or instead of the native view: while covered, and until the view repaints. */
|
||||
export function selectSnapshotWantsStill(state: EmbedSnapshotState, id: string | undefined, covered: boolean) {
|
||||
return covered || (state.status === "thawing" && state.id === id)
|
||||
}
|
||||
|
||||
/** The still Element Timing should report, or undefined when none waits for its frame. */
|
||||
|
|
@ -179,7 +197,7 @@ function syncStep(
|
|||
if (state.status === "frozen") {
|
||||
if (covered) return "keep"
|
||||
|
||||
return shown && state.url !== undefined ? "thaw" : "release"
|
||||
return shown ? "thaw" : "release"
|
||||
}
|
||||
|
||||
if (covered) return "refreeze"
|
||||
|
|
@ -208,7 +226,7 @@ function sync(
|
|||
}
|
||||
}
|
||||
|
||||
if (step === "thaw" && state.status === "frozen" && state.url !== undefined) {
|
||||
if (step === "thaw" && state.status === "frozen") {
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
|
|
@ -230,7 +248,8 @@ function release(state: EmbedSnapshotState): readonly EmbedSnapshotEffect[] {
|
|||
|
||||
if (state.status === "frozen") return state.url ? [{ type: "url.revoke", url: state.url }] : EMPTY_EFFECTS
|
||||
|
||||
if (state.status === "thawing") return [{ type: "thaw-timer.stop" }, { type: "url.revoke", url: state.url }]
|
||||
if (state.status === "thawing")
|
||||
return state.url ? [{ type: "thaw-timer.stop" }, { type: "url.revoke", url: state.url }] : THAW_STOP
|
||||
|
||||
return EMPTY_EFFECTS
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { createEffect, createMemo, createSignal, on, onCleanup, Show, untrack } from "solid-js"
|
||||
import { createEventListener } from "@solid-primitives/event-listener"
|
||||
import { createResizeObserver } from "@solid-primitives/resize-observer"
|
||||
import { observeReducedMotion, prefersReducedMotion } from "@opencode/ui/motion"
|
||||
import { embedBounds, overlaps } from "./embed-geometry"
|
||||
import { frameLoop, observeReducedMotion, prefersReducedMotion } from "@opencode/ui/motion"
|
||||
import type { EmbedProps, Embeds } from "@opencode/plugin/gui"
|
||||
import type { Bridge, BridgeLayout } from "@opencode/plugin/gui/host"
|
||||
import {
|
||||
|
|
@ -18,6 +18,7 @@ import {
|
|||
type EmbedStillEffect,
|
||||
type EmbedStillEvent,
|
||||
type EmbedStillState,
|
||||
type KeptStill,
|
||||
} from "./embed-flight-machine"
|
||||
import {
|
||||
INITIAL_SNAPSHOT_STATE,
|
||||
|
|
@ -25,6 +26,7 @@ import {
|
|||
selectSnapshotHidesNative,
|
||||
selectSnapshotNeedsSync,
|
||||
selectSnapshotUrl,
|
||||
selectSnapshotWantsStill,
|
||||
transitionEmbedSnapshot,
|
||||
type EmbedSnapshotEffect,
|
||||
type EmbedSnapshotEvent,
|
||||
|
|
@ -32,7 +34,9 @@ import {
|
|||
} from "./embed-snapshot-machine"
|
||||
|
||||
const geometry =
|
||||
/^(inset|left|right|top|bottom|translate|transform|scale|rotate|margin|padding|flex|grid|gap|row-gap|column-gap)|(^|-)(width|height)$/
|
||||
/^(inset|left|right|top|bottom|translate|transform|scale|rotate|margin|padding|flex|grid|gap|row-?gap|column-?gap)|(?:width|height)$/i
|
||||
|
||||
const overlay = '[data-floating-overlay], [data-popper-positioner]:not(:has([role="tooltip"])), [aria-modal="true"], dialog[open], :popover-open'
|
||||
|
||||
type Input = {
|
||||
readonly bridge: Bridge | undefined
|
||||
|
|
@ -95,11 +99,13 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
const documentVisible = createMemo(() => embedState().documentVisible)
|
||||
// Decoded flight stills, kept decoded so a flight's first frame paints them without a blank decode.
|
||||
const decodedStills = new Map<string, HTMLImageElement>()
|
||||
const [coverStill, setCoverStill] = createSignal<KeptStill>()
|
||||
|
||||
let element: HTMLDivElement | undefined
|
||||
let frame: number | undefined
|
||||
let frame: (() => void) | undefined
|
||||
let layout: string | undefined
|
||||
let until = 0
|
||||
const motions = new Set<Animation>()
|
||||
let settlePosition: ((rect: DOMRectReadOnly) => void) | undefined
|
||||
// The embed the last layout went to; it hides when another one takes the box.
|
||||
let placed: string | undefined
|
||||
let snapshotTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
|
@ -108,17 +114,26 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
const canvas = document.createElement("canvas")
|
||||
canvas.width = canvas.height = 1
|
||||
const paint = canvas.getContext("2d", { willReadFrequently: true })
|
||||
const colors = new Map<string, readonly [number, number, number, number]>()
|
||||
|
||||
// Let the browser resolve colors, including custom themes using color formats
|
||||
// that Electron's color parser cannot read.
|
||||
const resolve = (color: string) => {
|
||||
if (!paint) return undefined
|
||||
const kept = colors.get(color)
|
||||
|
||||
if (kept) return kept
|
||||
paint.clearRect(0, 0, 1, 1)
|
||||
paint.fillStyle = color
|
||||
paint.fillRect(0, 0, 1, 1)
|
||||
const data = paint.getImageData(0, 0, 1, 1).data
|
||||
|
||||
return [data[0], data[1], data[2], data[3]] as const
|
||||
const value = [data[0], data[1], data[2], data[3]] as const
|
||||
|
||||
if (colors.size >= 4) colors.clear()
|
||||
colors.set(color, value)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const revoke = (url: string) => {
|
||||
|
|
@ -229,6 +244,11 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
}
|
||||
|
||||
const hide = () => {
|
||||
setCoverStill(undefined)
|
||||
frame?.()
|
||||
frame = undefined
|
||||
layout = undefined
|
||||
|
||||
if (placed) props.bridge.embed(placed)
|
||||
placed = undefined
|
||||
|
||||
|
|
@ -238,14 +258,29 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
// The native embed always paints above the DOM, so hide it while a floating
|
||||
// menu, select, or popover overlaps it. Tooltips are excluded.
|
||||
const covered = (rect: DOMRect) => {
|
||||
const floating = document.querySelectorAll('[data-popper-positioner]:not(:has([role="tooltip"]))')
|
||||
if (!element) return false
|
||||
const floating = document.querySelectorAll(overlay)
|
||||
const layer = Number(element.closest<HTMLElement>("[data-dialog-layer]")?.dataset.dialogLayer ?? -1)
|
||||
|
||||
// An index loop: this runs every frame of a transition or a drag.
|
||||
for (let index = 0; index < floating.length; index++) {
|
||||
const r = floating[index].getBoundingClientRect()
|
||||
if (floating[index].contains(element)) continue
|
||||
// A dialog's own backdrop, and those of the dialogs beneath it, are behind an embed inside it.
|
||||
const backdrop = floating[index].getAttribute("data-dialog-backdrop")
|
||||
|
||||
if (r.width > 0 && r.left < rect.right && r.right > rect.left && r.top < rect.bottom && r.bottom > rect.top)
|
||||
return true
|
||||
if (backdrop !== null && Number(backdrop) <= layer) continue
|
||||
|
||||
if (overlaps(rect, floating[index].getBoundingClientRect())) return true
|
||||
}
|
||||
|
||||
// Surfaces portalled to the body after the embed's own root are above it even when nobody marked them, so an
|
||||
// unmarked menu or panel is covered rather than painted over.
|
||||
for (
|
||||
let portal = ancestorBelow(document.body, element)?.nextElementSibling;
|
||||
portal;
|
||||
portal = portal.nextElementSibling
|
||||
) {
|
||||
if (!portal.querySelector('[role="tooltip"]') && floats(portal, rect, 3)) return true
|
||||
}
|
||||
|
||||
return false
|
||||
|
|
@ -276,13 +311,11 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
if (!element) return
|
||||
const id = props.id
|
||||
|
||||
if (!id) return hide()
|
||||
if (!id) return
|
||||
const rect = element.getBoundingClientRect()
|
||||
const zoom = props.input.zoom()
|
||||
const left = Math.round(rect.left * zoom)
|
||||
const top = Math.round(rect.top * zoom)
|
||||
const right = Math.round(rect.right * zoom)
|
||||
const bottom = Math.round(rect.bottom * zoom)
|
||||
const bounds = embedBounds(rect, zoom)
|
||||
// A scaled preview scrolls the box inside an ancestor; only the part inside that scrollport is shown.
|
||||
const port = scrollport()
|
||||
const clip = port && scrollClip(port, rect, zoom)
|
||||
|
||||
|
|
@ -290,20 +323,17 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
props.visible &&
|
||||
current().documentVisible &&
|
||||
!props.input.moving() &&
|
||||
(!clip || (clip.width > 0 && clip.height > 0))
|
||||
(clip
|
||||
? clip.width > 0 && clip.height > 0
|
||||
: bounds.width > 0 && bounds.height > 0 && overlaps(rect, { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight }))
|
||||
|
||||
// A dialog's scrim covers the box like floating content does, so it dims a still of the page
|
||||
// instead of a blank box, and the page does not blink out and back as the dialog opens and closes.
|
||||
const cover =
|
||||
!!props.frozen ||
|
||||
props.input.dialog() ||
|
||||
(props.input.dialog() && !element.closest('[role="dialog"], [role="alertdialog"], dialog[open]')) ||
|
||||
covered(clip ? new DOMRect(clip.x / zoom, clip.y / zoom, clip.width / zoom, clip.height / zoom) : rect)
|
||||
|
||||
// Keep the embed on screen as a still under the floating content. The native view
|
||||
// stays visible until the still is on screen, so the box never flashes blank.
|
||||
syncSnapshot(id, shown, cover)
|
||||
const visible = shown && !selectSnapshotHidesNative(current().snapshot, id, cover)
|
||||
|
||||
// The cutout exposes the app backdrop outside the rounded card, not the embed inside it.
|
||||
const color =
|
||||
props.background ??
|
||||
|
|
@ -312,7 +342,31 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
const ring = props.radius ? cardRing(element) : undefined
|
||||
const viewport = { width: Math.round(window.innerWidth * zoom), height: Math.round(window.innerHeight * zoom) }
|
||||
|
||||
const next = `${id}:${visible}:${left}:${top}:${right}:${bottom}:${clip?.x}:${clip?.y}:${clip?.width}:${clip?.height}:${viewport.width}:${viewport.height}:${color}:${ring?.color}:${ring?.width}:${window.devicePixelRatio}`
|
||||
return { id, shown, cover, bounds, clip, color, ring, viewport, rect, zoom }
|
||||
}
|
||||
|
||||
const place = (boxLayout: NonNullable<ReturnType<typeof measure>>) => {
|
||||
const { id, shown, cover, bounds, clip, color, ring, viewport, rect, zoom } = boxLayout
|
||||
syncSnapshot(id, shown, cover)
|
||||
const still = current().still
|
||||
const kept = still.status !== "disposed" && still.kept
|
||||
const snapshot = current().snapshot
|
||||
|
||||
const warm =
|
||||
shown &&
|
||||
selectSnapshotWantsStill(snapshot, id, cover) &&
|
||||
kept &&
|
||||
kept.id === id &&
|
||||
kept.page === props.page &&
|
||||
kept.width === bounds.width / zoom &&
|
||||
kept.height === bounds.height / zoom
|
||||
? kept
|
||||
: undefined
|
||||
|
||||
setCoverStill(warm)
|
||||
const visible = shown && !selectSnapshotHidesNative(snapshot, id, cover, !!warm)
|
||||
|
||||
const next = `${id}:${visible}:${bounds.x}:${bounds.y}:${bounds.width}:${bounds.height}:${clip?.x}:${clip?.y}:${clip?.width}:${clip?.height}:${viewport.width}:${viewport.height}:${color}:${ring?.color}:${ring?.width}:${window.devicePixelRatio}`
|
||||
|
||||
if (next === layout) return
|
||||
layout = next
|
||||
|
|
@ -320,20 +374,19 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
const background = resolve(color)
|
||||
const border = ring && resolve(ring.color)
|
||||
|
||||
if (placed !== id) hide()
|
||||
placed = id
|
||||
|
||||
// The still lines up with the view's device-pixel-rounded bounds, so swapping one for the other moves nothing.
|
||||
// Electron takes integer DIPs. A DIP-rounded edge need not be an integer physical pixel on a scaled display.
|
||||
if (visible)
|
||||
dispatchStill({
|
||||
type: "placement.changed",
|
||||
page: props.page,
|
||||
placement: {
|
||||
id,
|
||||
x: left / zoom - rect.left,
|
||||
y: top / zoom - rect.top,
|
||||
width: Math.max(0, right - left) / zoom,
|
||||
height: Math.max(0, bottom - top) / zoom,
|
||||
x: bounds.x / zoom - rect.left,
|
||||
y: bounds.y / zoom - rect.top,
|
||||
width: bounds.width / zoom,
|
||||
height: bounds.height / zoom,
|
||||
},
|
||||
})
|
||||
|
||||
|
|
@ -341,7 +394,7 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
|
||||
const box: BridgeLayout = {
|
||||
visible,
|
||||
bounds: { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) },
|
||||
bounds,
|
||||
...(clip && { clip }),
|
||||
viewport,
|
||||
radius: Math.round((props.radius ?? 0) * zoom),
|
||||
|
|
@ -355,17 +408,26 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
)
|
||||
}
|
||||
|
||||
let measured: ReturnType<typeof measure>
|
||||
|
||||
const tick = () => {
|
||||
frame = undefined
|
||||
measure()
|
||||
|
||||
if (performance.now() < until) frame = requestAnimationFrame(tick)
|
||||
if (measured) place(measured)
|
||||
|
||||
motions.forEach((motion) => {
|
||||
if (motion.playState !== "running") motions.delete(motion)
|
||||
})
|
||||
|
||||
if (motions.size) schedule()
|
||||
|
||||
if (!motions.size && measured) settlePosition?.(measured.rect)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const schedule = (duration = 0) => {
|
||||
until = Math.max(until, performance.now() + duration)
|
||||
|
||||
if (frame === undefined) frame = requestAnimationFrame(tick)
|
||||
const schedule = () => {
|
||||
frame ??= frameLoop.addMeasured(() => { measured = measure() }, tick)
|
||||
}
|
||||
|
||||
// A navigation or reload makes the kept still another page's, as does another embed taking the box.
|
||||
|
|
@ -400,38 +462,168 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
// The native views are not clipped by the retained panel's DOM. Hide before the next
|
||||
// animation frame so closing the panel cannot leave the embed above the app.
|
||||
if (!props.visible || !documentVisible() || moving || !props.id) return hide()
|
||||
schedule(300)
|
||||
|
||||
if (placed && placed !== props.id) hide()
|
||||
schedule()
|
||||
},
|
||||
),
|
||||
)
|
||||
// Measure in the same frame as a resize, including when wrapped controls move a fixed-size embed.
|
||||
createResizeObserver(() => [element, element?.parentElement, scrollport()], measure)
|
||||
createEventListener(
|
||||
document,
|
||||
"scroll",
|
||||
(event) => {
|
||||
if (event.target instanceof Element && event.target.contains(element ?? null)) measure()
|
||||
},
|
||||
{ capture: true, passive: true },
|
||||
)
|
||||
createEventListener(window, "resize", () => schedule(300))
|
||||
// A layout transition elsewhere, such as the chat column's width while the side pane opens, can
|
||||
// move the box without resizing it. Track it from when it actually runs, and settle on its end.
|
||||
createEventListener(document, "transitionrun", (event) => {
|
||||
if (geometry.test(event.propertyName)) schedule(300)
|
||||
createEffect(() => {
|
||||
if (!element || !props.visible || !props.id || !documentVisible() || props.input.moving()) return
|
||||
const box = element
|
||||
// Watch the layout spine, not the conversation subtree: a sibling changing width or a banner being inserted
|
||||
// can move a fixed-size pane. Only the portals outside the app root need subtree observation (menus and toasts).
|
||||
const sizes = new ResizeObserver(schedule)
|
||||
const nodes = new Set<Element>()
|
||||
const neighbors = new Set<Element>()
|
||||
const removeScroll = () => nodes.forEach(node => node.removeEventListener("scroll", schedule))
|
||||
|
||||
const changes = new MutationObserver((records) => {
|
||||
if (!box.isConnected) {
|
||||
if (!nodes.size) return
|
||||
removeScroll()
|
||||
sizes.disconnect()
|
||||
changes.disconnect()
|
||||
changes.observe(document, { childList: true, subtree: true })
|
||||
hide()
|
||||
nodes.clear()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
!nodes.size ||
|
||||
records.some(
|
||||
(record) => record.type === "childList" && record.target instanceof Element && nodes.has(record.target),
|
||||
)
|
||||
)
|
||||
observe()
|
||||
schedule()
|
||||
})
|
||||
|
||||
const observe = () => {
|
||||
removeScroll()
|
||||
nodes.clear()
|
||||
neighbors.clear()
|
||||
sizes.disconnect()
|
||||
changes.disconnect()
|
||||
|
||||
if (!box.isConnected) {
|
||||
changes.observe(document, { childList: true, subtree: true })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for (let node: Element | null = box; node; node = node.parentElement) {
|
||||
nodes.add(node)
|
||||
node.addEventListener("scroll", schedule, { passive: true })
|
||||
sizes.observe(node)
|
||||
changes.observe(node, { attributes: true, childList: node !== box })
|
||||
|
||||
for (const sibling of node.parentElement?.children ?? []) {
|
||||
if (sibling === node) continue
|
||||
neighbors.add(sibling)
|
||||
sizes.observe(sibling)
|
||||
const portal = sibling.parentElement === document.body
|
||||
changes.observe(sibling, { attributes: true, childList: portal, characterData: portal, subtree: portal })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
observe()
|
||||
|
||||
const track = (target: Element) => {
|
||||
for (const motion of target.getAnimations()) {
|
||||
if (
|
||||
motion.effect instanceof KeyframeEffect &&
|
||||
motion.effect.target === target &&
|
||||
Number.isFinite(motion.effect.getComputedTiming().endTime) &&
|
||||
motion.effect.getKeyframes().some((key) => Object.keys(key).some((property) => geometry.test(property)))
|
||||
)
|
||||
motions.add(motion)
|
||||
}
|
||||
}
|
||||
|
||||
// Web Animations do not send CSS animation events. A tight intersection root wakes on the first displaced
|
||||
// edge, then the animation itself drives the frames; no permanent frame job or patched Element.animate.
|
||||
let position: IntersectionObserver | undefined
|
||||
|
||||
let previous: DOMRectReadOnly | undefined
|
||||
|
||||
const anchor = (rect: DOMRectReadOnly, visible = rect, threshold = 1, calibrated = false) => {
|
||||
previous = rect
|
||||
position?.disconnect()
|
||||
const inset = [visible.top, window.innerWidth - visible.right, window.innerHeight - visible.bottom, visible.left]
|
||||
position = new IntersectionObserver(([entry]) => {
|
||||
if (!entry || !box.isConnected) return
|
||||
const next = entry.boundingClientRect
|
||||
|
||||
if (next.x === rect.x && next.y === rect.y && next.width === rect.width && next.height === rect.height) {
|
||||
// With an ancestor scrollport the full box may never intersect. Pin the *visible* rectangle instead.
|
||||
if (!calibrated && entry.intersectionRatio > 0 && entry.intersectionRatio < 1)
|
||||
anchor(rect, entry.intersectionRect, entry.intersectionRatio * 0.999999, true)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
nodes.forEach(track)
|
||||
neighbors.forEach(track)
|
||||
schedule()
|
||||
|
||||
if (motions.size) {
|
||||
position?.disconnect()
|
||||
previous = undefined
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
anchor(next)
|
||||
}, { rootMargin: inset.map((n) => `${-Math.floor(n)}px`).join(" "), threshold })
|
||||
position.observe(box)
|
||||
}
|
||||
|
||||
anchor(box.getBoundingClientRect())
|
||||
settlePosition = (rect) => {
|
||||
if (!previous || rect.x !== previous.x || rect.y !== previous.y || rect.width !== previous.width || rect.height !== previous.height) anchor(rect)
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
position?.disconnect()
|
||||
settlePosition = undefined
|
||||
})
|
||||
createEventListener(document, ["transitionrun", "transitionstart", "animationstart"], (event) => {
|
||||
const target = event.target
|
||||
|
||||
if (!(target instanceof Element) || (!nodes.has(target) && !neighbors.has(target) && !target.matches(overlay))) return
|
||||
track(target)
|
||||
|
||||
schedule()
|
||||
})
|
||||
createEventListener(document, "scroll", schedule, { passive: true })
|
||||
const scale = () => window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`)
|
||||
let density = scale()
|
||||
|
||||
const changed = () => {
|
||||
density.removeEventListener("change", changed)
|
||||
density = scale()
|
||||
density.addEventListener("change", changed)
|
||||
schedule()
|
||||
}
|
||||
|
||||
density.addEventListener("change", changed)
|
||||
onCleanup(() => density.removeEventListener("change", changed))
|
||||
createEventListener(window, "resize", schedule)
|
||||
createEventListener(document, "toggle", (event) => {
|
||||
if (event.target instanceof Element && event.target.matches("[popover], dialog")) schedule()
|
||||
}, true)
|
||||
createEventListener(window.matchMedia("(prefers-color-scheme: dark)"), "change", schedule)
|
||||
onCleanup(() => {
|
||||
removeScroll()
|
||||
motions.clear()
|
||||
changes.disconnect()
|
||||
sizes.disconnect()
|
||||
})
|
||||
})
|
||||
createEventListener(document, ["transitionend", "transitioncancel"], (event) => {
|
||||
if (geometry.test(event.propertyName)) schedule()
|
||||
})
|
||||
// Floating content portals directly into <body>; keep measuring briefly so
|
||||
// the positioner has settled before the overlap check runs.
|
||||
const portals = new MutationObserver(() => schedule(300))
|
||||
portals.observe(document.body, { childList: true })
|
||||
onCleanup(() => portals.disconnect())
|
||||
const appearance = new MutationObserver(() => schedule(300))
|
||||
appearance.observe(document.documentElement, { attributes: true, attributeFilter: ["style", "data-theme", "dir"] })
|
||||
onCleanup(() => appearance.disconnect())
|
||||
createEventListener(window.matchMedia("(prefers-color-scheme: dark)"), "change", () => schedule(300))
|
||||
createEventListener(document, "visibilitychange", () =>
|
||||
setEmbedState({ ...current(), documentVisible: document.visibilityState === "visible" }),
|
||||
)
|
||||
|
|
@ -449,7 +641,6 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
),
|
||||
)
|
||||
onCleanup(() => {
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
hide()
|
||||
// Stops every timer and gives up every still, including ones still decoding.
|
||||
dispatchSnapshot(DISPOSED_EVENT)
|
||||
|
|
@ -460,7 +651,12 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
|
||||
const snapshotUrl = createMemo(() => selectSnapshotUrl(embedState().snapshot, props.id, props.visible))
|
||||
|
||||
const flightStill = createMemo(() => selectFlightStill(embedState().flight, embedState().still, props.id, props.page))
|
||||
// A warm still stays under a fresh capture until a frame has presented it.
|
||||
const flightStill = createMemo(
|
||||
() =>
|
||||
selectFlightStill(embedState().flight, embedState().still, props.id, props.page) ??
|
||||
(selectPaintingUrl(embedState().snapshot) || !snapshotUrl() ? coverStill() : undefined),
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={element} class={props.class}>
|
||||
|
|
@ -495,6 +691,31 @@ function EmbedView(props: EmbedProps & { input: Input; bridge: Bridge }) {
|
|||
)
|
||||
}
|
||||
|
||||
// The child of `root` that contains `node`.
|
||||
function ancestorBelow(root: Element, node: Element) {
|
||||
for (let current: Element | null = node; current; current = current.parentElement) {
|
||||
if (current.parentElement === root) return current
|
||||
}
|
||||
}
|
||||
|
||||
// Whether a visible, positioned surface that takes input, `depth` levels into a portal at most, overlaps the box. A
|
||||
// wrapper that lets input through is transparent: a full-window portal container never counts, only what it holds.
|
||||
function floats(node: Element, rect: DOMRect, depth: number): boolean {
|
||||
// Marked surfaces were measured with their dialog layer.
|
||||
if (node.matches(overlay)) return false
|
||||
const style = getComputedStyle(node)
|
||||
|
||||
if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") return false
|
||||
|
||||
if ((style.position === "fixed" || style.position === "absolute") && style.pointerEvents !== "none") {
|
||||
const box = node.getBoundingClientRect()
|
||||
|
||||
if (box.width > 1 && box.height > 1 && overlaps(rect, box)) return true
|
||||
}
|
||||
|
||||
return depth > 0 && Array.from(node.children).some((child) => floats(child, rect, depth - 1))
|
||||
}
|
||||
|
||||
// The client box excludes the scrollbar track, including a left-side RTL scrollbar.
|
||||
function scrollClip(port: HTMLElement, rect: DOMRect, zoom: number) {
|
||||
const area = port.getBoundingClientRect()
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ import {
|
|||
type StorageScope,
|
||||
type Tabs,
|
||||
} from "@opencode/plugin/gui"
|
||||
import { BuiltinPanel, type BuiltinStoreFrom, type BuiltinStoreOptions } from "@opencode/plugin/gui/builtin"
|
||||
import { BuiltinPanel, BuiltinPromptGate, type BuiltinStoreFrom, type BuiltinStoreOptions } from "@opencode/plugin/gui/builtin"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { same } from "@/runtime/persistence/equality"
|
||||
import { Persist, persisted, removePersisted } from "@/runtime/persistence/storage"
|
||||
|
|
@ -53,6 +53,7 @@ import { useCurrentRoute, useLayout } from "@/shell/state/layout"
|
|||
import { sessionPaneTab, sessionTabPane, type SessionPane } from "@/shell/state/session-tabs"
|
||||
import { terminalFontFamily, useSettings } from "@/settings/model"
|
||||
import { useSettingsSurface } from "@/settings/surface"
|
||||
import { fitsSidePane } from "@/session/session-panel-width"
|
||||
import { formatKeybindParts, useCommand } from "@/shell/commands/command"
|
||||
import { createMediaQuery } from "@solid-primitives/media"
|
||||
import { useIsRouting, useLocation } from "@solidjs/router"
|
||||
|
|
@ -73,6 +74,7 @@ import {
|
|||
createProjectRequestState,
|
||||
createSideRegionState,
|
||||
selectMobileView,
|
||||
selectPanelState,
|
||||
selectWaitingProjectServer,
|
||||
transitionMobileView,
|
||||
transitionProjectRequest,
|
||||
|
|
@ -83,6 +85,7 @@ import {
|
|||
} from "./host-layout-machine"
|
||||
import { usePluginHost, type HostApiFactories } from "./host"
|
||||
import { createLocatedWrites } from "./located"
|
||||
import { settlePromptGates } from "./prompt-gate"
|
||||
import { createSessionPanelMenu } from "./panel-menu"
|
||||
import type { Region } from "./panels"
|
||||
import {
|
||||
|
|
@ -312,9 +315,7 @@ export function createHostApis() {
|
|||
return true
|
||||
},
|
||||
openExternal(url) {
|
||||
if (platform.openLocalFile && URL.canParse(url) && new URL(url).protocol === "file:")
|
||||
return platform.openLocalFile(url)
|
||||
platform.openExternal(url)
|
||||
if (/^(?:https?:\/\/|mailto:)/i.test(url) && URL.canParse(url)) platform.openExternal(url)
|
||||
},
|
||||
}),
|
||||
desktop: () =>
|
||||
|
|
@ -460,6 +461,7 @@ export function createHostApis() {
|
|||
// Before the interface mounts, reads return what an empty layout holds and writes wait for it.
|
||||
layout: (plugin) => ({
|
||||
narrow,
|
||||
fitsSide: () => fitsSidePane(document.querySelector("[data-pane-row]")?.getBoundingClientRect().width ?? 0),
|
||||
ready: () => current()?.layout.ready() ?? false,
|
||||
open: (key, session, options) => write((value) => value.layout.open(key, session, options)),
|
||||
close: (key, session) => write((value) => value.layout.close(key, session)),
|
||||
|
|
@ -859,6 +861,13 @@ export function createPluginAttachment(apis: HostApis) {
|
|||
})
|
||||
}
|
||||
|
||||
// Opening the tab a pane already selects changes no selection, so a New tab view over it would stay. The region
|
||||
// hears of the open before the write, while the pane's selection is still the one on screen, and replaces that view
|
||||
// as a tab that becomes the selection does.
|
||||
const uncover = (session: SessionRef, key: string) => {
|
||||
if (mountedSession(session)) region()?.opening(key)
|
||||
}
|
||||
|
||||
const place = (key: string, session: SessionRef, value: string, options: OpenOptions | undefined) => {
|
||||
const item = provider(key)
|
||||
const placement = options?.tab ?? "open"
|
||||
|
|
@ -869,6 +878,7 @@ export function createPluginAttachment(apis: HostApis) {
|
|||
// A select keeps the narrow-screen view, as a background open does, and shows the tab's pane too.
|
||||
if (placement === "select")
|
||||
return batch(() => {
|
||||
uncover(session, key)
|
||||
layout.panel.append(value, key)
|
||||
layout.panel.focus(value, key)
|
||||
reveal(session, value, key)
|
||||
|
|
@ -885,6 +895,8 @@ export function createPluginAttachment(apis: HostApis) {
|
|||
if (mountedSession(session) && !known.some((entry) => entry.key === key && !entry.tab.transient)) return
|
||||
}
|
||||
|
||||
uncover(session, key)
|
||||
|
||||
// Pinned tabs are listed without being stored; opening one only selects it.
|
||||
if (known.some((entry) => entry.key === key && entry.tab.pinned)) layout.panel.focus(value, key)
|
||||
else if (placement === "preview") layout.panel.preview(value, key, transient)
|
||||
|
|
@ -945,9 +957,12 @@ export function createPluginAttachment(apis: HostApis) {
|
|||
const pane = mounted ? mounted.paneOf(key) : sessionTabPane(panel, key)
|
||||
const shown = mounted ? mounted.pane(pane).active() : sessionPaneTab(panel, pane)
|
||||
|
||||
if (shown !== key) return panel.all.includes(key) ? "open" : "closed"
|
||||
|
||||
return paneOpened(session, pane) ? "visible" : "active"
|
||||
return selectPanelState({
|
||||
stored: panel.all.includes(key),
|
||||
selected: shown === key,
|
||||
covered: !!mounted?.newTab(pane),
|
||||
paneOpen: paneOpened(session, pane),
|
||||
})
|
||||
}
|
||||
|
||||
const hide = (key: string, session: SessionRef) =>
|
||||
|
|
@ -1224,6 +1239,17 @@ export function createPluginAttachment(apis: HostApis) {
|
|||
attach: () => apis.attach(mounted),
|
||||
/** The routed `MountedSession`. */
|
||||
current,
|
||||
/**
|
||||
* What a send to a session waits for before its request goes out: the `BuiltinPromptGate` of every plugin that
|
||||
* ships with the app, which prepares the session for its next step. A session no open tab owns has no gate.
|
||||
*/
|
||||
ready(server: string, sessionID: string) {
|
||||
const session = untrack(sessions).find((item) => item.key === `${server}\n${sessionID}`)
|
||||
|
||||
if (!session) return Promise.resolve()
|
||||
|
||||
return settlePromptGates(untrack(() => host.items(BuiltinPromptGate)), host.builtin, session)
|
||||
},
|
||||
closed,
|
||||
/** Opens and selects a side tab by key, as a reopened closed tab comes back. */
|
||||
openTab: (key: string, session: SessionRef) => open(key, session, { tab: "select" }),
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {
|
|||
MOBILE_VIEW_PENDING_TTL_MS,
|
||||
PROJECT_REQUEST_TTL_MS,
|
||||
selectMobileView,
|
||||
selectPanelState,
|
||||
selectSideRegionSession,
|
||||
transitionMobileView,
|
||||
transitionProjectRequest,
|
||||
|
|
@ -198,3 +199,16 @@ test("a request for a listed server opens the picker at once", () => {
|
|||
run.dispatch({ type: "request", server: "local", title: "Open", listed: true })
|
||||
expect(run.effects).toEqual([{ type: "open.picker", server: "local", title: "Open" }])
|
||||
})
|
||||
|
||||
// `Layout.state` tells a plugin whether the person sees its tab. The browser reads it to decide whether a page the
|
||||
// agent shows must be brought to the front: a tab under the "+" New tab view reported `visible` and stayed hidden.
|
||||
test.each([
|
||||
["the pane's tab, on screen", { stored: true, selected: true, covered: false, paneOpen: true }, "visible"],
|
||||
["the pane's tab, pane hidden", { stored: true, selected: true, covered: false, paneOpen: false }, "active"],
|
||||
["the pane's tab under a New tab view", { stored: true, selected: true, covered: true, paneOpen: true }, "open"],
|
||||
["under a New tab view, pane hidden", { stored: true, selected: true, covered: true, paneOpen: false }, "open"],
|
||||
["another tab of the strip", { stored: true, selected: false, covered: false, paneOpen: true }, "open"],
|
||||
["not in the strip", { stored: false, selected: false, covered: false, paneOpen: true }, "closed"],
|
||||
] as const)("a panel key's state: %s", (_label, input, expected) => {
|
||||
expect(selectPanelState(input)).toBe(expected)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,4 +1,23 @@
|
|||
import type { OpenOptions } from "@opencode/plugin/gui"
|
||||
import type { OpenOptions, PanelState } from "@opencode/plugin/gui"
|
||||
|
||||
/**
|
||||
* Where a panel key stands in a session, as `Layout.state` reports it. A New tab view shown in the key's pane covers
|
||||
* the tab the pane selects: that tab is still in the strip, but it is not the one its pane shows.
|
||||
*/
|
||||
export function selectPanelState(input: {
|
||||
/** The key is in the session's strip. */
|
||||
readonly stored: boolean
|
||||
/** The key is the tab its pane selects. */
|
||||
readonly selected: boolean
|
||||
/** A New tab view shows in the key's pane, over the tab the pane selects. */
|
||||
readonly covered: boolean
|
||||
/** The key's pane is on screen. */
|
||||
readonly paneOpen: boolean
|
||||
}): PanelState {
|
||||
if (!input.selected || input.covered) return input.stored ? "open" : "closed"
|
||||
|
||||
return input.paneOpen ? "visible" : "active"
|
||||
}
|
||||
|
||||
/** A narrow-screen view selected for a session that is not routed waits this long for the navigation that routes it. */
|
||||
export const MOBILE_VIEW_PENDING_TTL_MS = 5_000
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@ type Instance = {
|
|||
export type PluginInput = { readonly options: PluginOptions; readonly client: () => OpenCodeClient | undefined }
|
||||
|
||||
/** The APIs a window context exposes as properties. */
|
||||
type HostApis = Omit<BuiltinContext, keyof BaseContext | "provide" | "use" | "main">
|
||||
type HostApis = Omit<BuiltinContext, keyof BaseContext | "provide" | "provideFor" | "use" | "main">
|
||||
|
||||
/**
|
||||
* Creates one HostApi for a plugin instance, on the instance's first read of it. `register` withdraws what it is
|
||||
|
|
@ -194,7 +194,7 @@ export function PluginHostProvider(props: ParentProps<HostInput>) {
|
|||
function createHost(input: HostInput) {
|
||||
const language = useLanguage()
|
||||
const owner = getOwner()
|
||||
const provided = new Map<string, { live: Live<unknown> & { readonly status: "active" } }>()
|
||||
const provided = new Map<string, (consumer: string, signal: AbortSignal) => Live<unknown>>()
|
||||
const generations = new Map<string, number>()
|
||||
|
||||
// Entries are indexed by registry and contracts versioned by token, so a change wakes only its own readers.
|
||||
|
|
@ -274,10 +274,10 @@ function createHost(input: HostInput) {
|
|||
return pending
|
||||
}
|
||||
|
||||
const contractLive = (token: Contract<unknown>): Live<unknown> => {
|
||||
const contractLive = (token: Contract<unknown>, consumer: string, signal: AbortSignal): Live<unknown> => {
|
||||
void state.contracts[token.id]
|
||||
|
||||
return provided.get(token.id)?.live ?? absent(token.id, false)
|
||||
return provided.get(token.id)?.(consumer, signal) ?? absent(token.id, false)
|
||||
}
|
||||
|
||||
// Reuses each item object while its value is unchanged so keyed renders do not remount.
|
||||
|
|
@ -695,7 +695,7 @@ function createHost(input: HostInput) {
|
|||
|
||||
if (existing) return existing
|
||||
|
||||
const read = liveAccessor(token.kind === "contract" ? () => contractLive(token) : () => ipcLive(token))
|
||||
const read = liveAccessor(token.kind === "contract" ? () => contractLive(token, plugin, controller.signal) : () => ipcLive(token))
|
||||
|
||||
lives.set(token.id, read)
|
||||
|
||||
|
|
@ -858,6 +858,9 @@ function createHost(input: HostInput) {
|
|||
provide<T>(token: Contract<T> | Ipc, impl: T) {
|
||||
if (token.kind === "ipc") throw new Error("Ipcs are provided by a plugin's main entry")
|
||||
|
||||
return context.provideFor(token, () => impl)
|
||||
},
|
||||
provideFor<T>(token: Contract<T>, bind: (consumer: string, signal: AbortSignal) => T) {
|
||||
if (!owns(plugin, token.id)) throw new Error(`${plugin} provides only its own contracts, not "${token.id}"`)
|
||||
|
||||
if (late()) return () => {}
|
||||
|
|
@ -866,7 +869,17 @@ function createHost(input: HostInput) {
|
|||
|
||||
generations.set(token.id, generation)
|
||||
|
||||
const entry = { live: { status: "active", value: impl, generation } as const }
|
||||
const clients = new WeakMap<AbortSignal, Live<T>>()
|
||||
|
||||
const entry = (consumer: string, signal: AbortSignal) => {
|
||||
const previous = clients.get(signal)
|
||||
|
||||
if (previous) return previous
|
||||
const live = { status: "active", value: untrack(() => bind(consumer, signal)), generation } as const
|
||||
clients.set(signal, live)
|
||||
|
||||
return live
|
||||
}
|
||||
|
||||
provided.set(token.id, entry)
|
||||
setState("contracts", token.id, (version = 0) => version + 1)
|
||||
|
|
@ -1015,6 +1028,8 @@ function createHost(input: HostInput) {
|
|||
serversReady: createMemo(() => selectServersReady(startup.state())),
|
||||
/** The plugins main lists; empty on the web and until main answers. */
|
||||
installed: createMemo(() => selectInstalled(startup.state())),
|
||||
/** Whether the plugin ships with the app. What only built-ins may contribute is read through it. */
|
||||
builtin: (id: string) => input.builtins?.has(id) ?? false,
|
||||
/** A plugin's main entry cannot answer. Reactive. */
|
||||
mainFailed: (id: string) => selectMainFailed(startup.state(), id),
|
||||
/** Reports what the startup gate waits for. */
|
||||
|
|
|
|||
|
|
@ -114,6 +114,17 @@ describe("new tab machine", () => {
|
|||
expect(result.state.panes.side).toEqual({ ids: ["new:1"], chosen: undefined })
|
||||
})
|
||||
|
||||
test("opening the tab the pane already selects replaces the New tab shown over it", () => {
|
||||
const region: Region = { regionActive: "a", side: { active: "a", keys: ["a", "b"] } }
|
||||
const opened: NewTabsEvent[] = [sync(region), { type: "open", pane: "side" }, { type: "open", pane: "side" }]
|
||||
const result = run([...opened, { type: "open.selected", pane: "side" }, sync(region)])
|
||||
|
||||
// Only the shown one goes, as when another tab selects itself; with none shown the event changes nothing.
|
||||
expect(result.state.panes.side).toEqual({ ids: ["new:1"], chosen: undefined })
|
||||
expect(shown(result.state, region, "side")).toBeUndefined()
|
||||
expect(transitionNewTabs(result.state, { type: "open.selected", pane: "side" }).state).toBe(result.state)
|
||||
})
|
||||
|
||||
test("a split pane that loses its last tab takes its New tabs and choice with it", () => {
|
||||
const open: Region = { regionActive: "t", side: none, split: { active: "t", keys: ["t"] } }
|
||||
const closed: Region = { side: { active: "a", keys: ["a"] } }
|
||||
|
|
|
|||
|
|
@ -46,6 +46,11 @@ export type NewTabsEvent =
|
|||
| { readonly type: "select.new"; readonly pane: SessionPane; readonly id: string }
|
||||
/** The user selects a tab of the pane, which shows over its New tabs. */
|
||||
| { readonly type: "select.tab"; readonly pane: SessionPane }
|
||||
/**
|
||||
* A tab opens in the pane that already selects it. The open changes no selection for `sync` to see, so this replaces
|
||||
* the New tab the pane shows over it, as a tab that selects itself does.
|
||||
*/
|
||||
| { readonly type: "open.selected"; readonly pane: SessionPane }
|
||||
/** `empty`: the strip holds no tab, so closing the last New tab empties the region. */
|
||||
| { readonly type: "dismiss"; readonly id: string; readonly empty: boolean }
|
||||
|
||||
|
|
@ -82,6 +87,18 @@ export function transitionNewTabs(state: NewTabsState, event: NewTabsEvent): New
|
|||
return { state: withPane(state, event.pane, { ids: pane.ids, chosen: undefined }), effects: [] }
|
||||
}
|
||||
|
||||
if (event.type === "open.selected") {
|
||||
// The pane selects a tab, so the New tab it shows is the chosen one.
|
||||
const pane = state.panes[event.pane]
|
||||
|
||||
if (pane.chosen === undefined) return { state, effects: [] }
|
||||
|
||||
return {
|
||||
state: withPane(state, event.pane, { ids: pane.ids.filter((id) => id !== pane.chosen), chosen: undefined }),
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
|
||||
const owner = SESSION_PANES.find((pane) => state.panes[pane].ids.includes(event.id))
|
||||
|
||||
if (!owner) return { state, effects: [] }
|
||||
|
|
|
|||
|
|
@ -228,6 +228,7 @@ export function createPaneDrag(input: {
|
|||
{(target) => (
|
||||
<div
|
||||
data-slot={target().strip ? "pane-drop-indicator" : "pane-drop-zone"}
|
||||
data-floating-overlay
|
||||
data-pane={target().pane}
|
||||
class="absolute"
|
||||
classList={{
|
||||
|
|
@ -247,6 +248,7 @@ export function createPaneDrag(input: {
|
|||
<div
|
||||
class="absolute max-w-60 h-7 px-2.5 flex items-center rounded-md bg-v2-background-bg-base text-13-regular text-v2-text-text-base truncate shadow-[var(--v2-elevation-raised)] opacity-90"
|
||||
style={{ left: `${current().x + 12}px`, top: `${current().y + 12}px` }}
|
||||
data-floating-overlay
|
||||
>
|
||||
{current().title}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -413,6 +413,15 @@ export function createRegion(input: {
|
|||
input.tabs().setActive(key)
|
||||
})
|
||||
},
|
||||
/**
|
||||
* A tab is about to open. When its pane already selects it, the open changes no selection, so the New tab the pane
|
||||
* shows over it is replaced here; any other open replaces it by becoming the selection.
|
||||
*/
|
||||
opening(key: string) {
|
||||
const pane = paneOfKey(key)
|
||||
|
||||
if (untrack(panes[pane].active) === key) dispatchNewTabs({ type: "open.selected", pane })
|
||||
},
|
||||
/** The new tab views of a pane, by id in strip order. */
|
||||
newTabs,
|
||||
/** The id of the new tab view a pane shows: the chosen one, else the newest while the pane selects no tab. */
|
||||
|
|
|
|||
113
packages/app/src/runtime/plugin/prompt-gate.test.ts
Normal file
113
packages/app/src/runtime/plugin/prompt-gate.test.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import { afterEach, beforeEach, expect, jest, test } from "bun:test"
|
||||
import { Registry, type SessionRef } from "@opencode/plugin/gui"
|
||||
import { BuiltinPromptGate } from "@opencode/plugin/gui/builtin"
|
||||
import { PROMPT_GATE_TIMEOUT_MS, settlePromptGates } from "./prompt-gate"
|
||||
|
||||
// SAFETY: the gates under test receive the ref and never read it.
|
||||
const session = { key: "server\nses_alpha", id: "ses_alpha" } as SessionRef
|
||||
|
||||
// The gates of one built-in, as the host lists a registry's items.
|
||||
const builtins = (...gates: BuiltinPromptGate[]) => gates.map((value) => ({ plugin: "browser", value }))
|
||||
|
||||
const shipped = (plugin: string) => plugin === "browser"
|
||||
|
||||
beforeEach(() => void jest.useFakeTimers())
|
||||
|
||||
afterEach(() => void jest.useRealTimers())
|
||||
|
||||
// Runs the promise jobs queued so far, which the fake clock does not.
|
||||
const settle = async (promise: Promise<void>) => {
|
||||
const state = { done: false }
|
||||
void promise.then(() => (state.done = true))
|
||||
|
||||
// More turns than the longest chain here: a gate, allSettled, the race and its cleanup.
|
||||
for (const _ of Array.from({ length: 16 })) await Promise.resolve()
|
||||
|
||||
return state.done
|
||||
}
|
||||
|
||||
test("a send waits for every gate, and not for the timeout once they settled", async () => {
|
||||
const slow = Promise.withResolvers<void>()
|
||||
const signals: AbortSignal[] = []
|
||||
|
||||
const waiting = settlePromptGates(
|
||||
builtins(
|
||||
{ ready: (input) => void signals.push(input.signal) },
|
||||
{ ready: () => slow.promise },
|
||||
// A gate that throws or rejects is another plugin's fault, never the prompt's.
|
||||
{ ready: () => Promise.reject(new Error("gate failed")) },
|
||||
{
|
||||
ready: () => {
|
||||
throw new Error("gate threw")
|
||||
},
|
||||
},
|
||||
),
|
||||
shipped,
|
||||
session,
|
||||
)
|
||||
|
||||
expect(await settle(waiting)).toBe(false)
|
||||
slow.resolve()
|
||||
expect(await settle(waiting)).toBe(true)
|
||||
// The host stopped waiting.
|
||||
expect(signals.map((signal) => signal.aborted)).toEqual([true])
|
||||
})
|
||||
|
||||
test("a gate that never settles holds the send for one second and no longer", async () => {
|
||||
const signals: AbortSignal[] = []
|
||||
|
||||
const waiting = settlePromptGates(
|
||||
builtins({
|
||||
ready: (input) => {
|
||||
signals.push(input.signal)
|
||||
|
||||
return new Promise<void>(() => undefined)
|
||||
},
|
||||
}),
|
||||
shipped,
|
||||
session,
|
||||
)
|
||||
|
||||
expect(PROMPT_GATE_TIMEOUT_MS).toBe(1_000)
|
||||
jest.advanceTimersByTime(PROMPT_GATE_TIMEOUT_MS - 1)
|
||||
expect(await settle(waiting)).toBe(false)
|
||||
expect(signals[0]?.aborted).toBe(false)
|
||||
jest.advanceTimersByTime(1)
|
||||
expect(await settle(waiting)).toBe(true)
|
||||
expect(signals[0]?.aborted).toBe(true)
|
||||
})
|
||||
|
||||
test("a send with no gate does not wait", async () => {
|
||||
expect(await settle(settlePromptGates([], shipped, session))).toBe(true)
|
||||
})
|
||||
|
||||
// The registry is in the workspace-only SDK, but a registry is its id: a plugin bundle can make the same token with
|
||||
// the public SDK and add an item under it.
|
||||
test("a plugin bundle that registers a prompt gate is never asked, and holds no send", async () => {
|
||||
expect(Registry.define<BuiltinPromptGate>("prompt-gate").id).toBe(BuiltinPromptGate.id)
|
||||
const asked: string[] = []
|
||||
|
||||
const waiting = settlePromptGates(
|
||||
[
|
||||
{ plugin: "browser", value: { ready: () => void asked.push("browser") } },
|
||||
{
|
||||
plugin: "acme-bundle",
|
||||
value: {
|
||||
ready: (input) => {
|
||||
asked.push(`acme-bundle ${input.session.id}`)
|
||||
|
||||
return new Promise<void>(() => undefined)
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
shipped,
|
||||
session,
|
||||
)
|
||||
|
||||
expect(await settle(waiting)).toBe(true)
|
||||
expect(asked).toEqual(["browser"])
|
||||
// With only a bundle's gate there is nothing to wait for, and no timer either.
|
||||
const bundle = { plugin: "acme-bundle", value: { ready: () => new Promise<void>(() => undefined) } }
|
||||
expect(await settle(settlePromptGates([bundle], shipped, session))).toBe(true)
|
||||
})
|
||||
36
packages/app/src/runtime/plugin/prompt-gate.ts
Normal file
36
packages/app/src/runtime/plugin/prompt-gate.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import type { SessionRef } from "@opencode/plugin/gui"
|
||||
import type { BuiltinPromptGate } from "@opencode/plugin/gui/builtin"
|
||||
|
||||
/**
|
||||
* How long a prompt waits for the plugins' gates before it is sent anyway. A gate that misses it costs the model one
|
||||
* step without what the gate prepared; a second of dead time on Enter is the most that is worth.
|
||||
*/
|
||||
export const PROMPT_GATE_TIMEOUT_MS = 1_000
|
||||
|
||||
/**
|
||||
* Resolves once every gate settled or the timeout passed, whichever is first; it never rejects. Only the gates of
|
||||
* plugins that ship with the app are asked (`builtin`): the registry is theirs alone, and a plugin bundle that adds
|
||||
* an item under its id would otherwise hold every prompt and learn which session it goes to.
|
||||
*/
|
||||
export function settlePromptGates(
|
||||
items: readonly { readonly plugin: string; readonly value: BuiltinPromptGate }[],
|
||||
builtin: (plugin: string) => boolean,
|
||||
session: SessionRef,
|
||||
) {
|
||||
const gates = items.flatMap((item) => (builtin(item.plugin) ? [item.value] : []))
|
||||
|
||||
if (gates.length === 0) return Promise.resolve()
|
||||
const controller = new AbortController()
|
||||
const settled = Promise.withResolvers<void>()
|
||||
const timer = setTimeout(settled.resolve, PROMPT_GATE_TIMEOUT_MS)
|
||||
|
||||
// Promise.try keeps a gate that throws to itself, so the others still run.
|
||||
void Promise.allSettled(
|
||||
gates.map((gate) => Promise.try(() => gate.ready({ session, signal: controller.signal }))),
|
||||
).then(() => settled.resolve())
|
||||
|
||||
return settled.promise.finally(() => {
|
||||
clearTimeout(timer)
|
||||
controller.abort()
|
||||
})
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@ import {
|
|||
type ParentProps,
|
||||
} from "solid-js"
|
||||
import { Portal, render } from "solid-js/web"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import {
|
||||
MarkdownProvider,
|
||||
useMarkdown,
|
||||
|
|
@ -33,10 +34,15 @@ import {
|
|||
type CodeBlockProps,
|
||||
type MountedSession,
|
||||
} from "@opencode/plugin/gui"
|
||||
import { BuiltinSlot, type BuiltinSlotMap } from "@opencode/plugin/gui/builtin"
|
||||
import { BuiltinAppLink, BuiltinSlot, type BuiltinSlotMap } from "@opencode/plugin/gui/builtin"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
import { appLinkRoute, createAppLinks } from "./app-links"
|
||||
import { PluginContext } from "@opencode/plugin/gui/host"
|
||||
import { usePluginHost, type Item } from "./host"
|
||||
import { createLinkCheck } from "./link-check"
|
||||
import { webHref } from "./web-href"
|
||||
|
||||
/**
|
||||
* Renders one plugin contribution with its context and error isolation: a contribution that throws records the
|
||||
|
|
@ -154,6 +160,7 @@ export function PluginThemes(props: { loaded: () => boolean }) {
|
|||
export function PluginLinks(props: ParentProps<{ session: MountedSession; active?: boolean }>) {
|
||||
const host = usePluginHost()
|
||||
const markdown = useMarkdown()
|
||||
const desktop = usePlatform().platform === "desktop"
|
||||
|
||||
// Checks untracked: markdown calls this inside its render effect, which must not follow the routed session.
|
||||
const localFileExists = createLinkCheck(
|
||||
|
|
@ -163,6 +170,7 @@ export function PluginLinks(props: ParentProps<{ session: MountedSession; active
|
|||
|
||||
const Links = (inner: ParentProps<{ codeBlocks: MarkdownCodeBlocks | false }>) => (
|
||||
<MarkdownProvider
|
||||
appLinks={desktop}
|
||||
readImage={markdown?.readImage}
|
||||
openLocalFile={(href) => void host.links.open({ href, session: props.session })}
|
||||
localFileExists={localFileExists}
|
||||
|
|
@ -187,6 +195,48 @@ export function PluginLinks(props: ParentProps<{ session: MountedSession; active
|
|||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Offers a plain click on a web link in the session screen (its conversation and side panels) to the LinkHandler
|
||||
* contributions first, as `Links.open({ href, session })`. A click with a modifier key, or one no handler takes, keeps
|
||||
* the link's own behavior: the system browser.
|
||||
*/
|
||||
export function createWebLinks(session: () => MountedSession) {
|
||||
const host = usePluginHost()
|
||||
const language = useLanguage()
|
||||
const platform = usePlatform()
|
||||
|
||||
if (platform.platform === "desktop") createAppLinks((href) => {
|
||||
const handler = host.items(BuiltinAppLink)[0]
|
||||
const route = appLinkRoute(href, !!handler)
|
||||
|
||||
if (route === "mail") return platform.openExternal(href)
|
||||
|
||||
if (route === "review") return handler?.value.review(href)
|
||||
void navigator.clipboard.writeText(href).then(
|
||||
() => showToast({ title: language.t("common.copied") }),
|
||||
() => showToast({ title: language.t("common.requestFailed") }),
|
||||
)
|
||||
})
|
||||
|
||||
makeEventListener(document, "click", (event) => {
|
||||
const href = webLink(event, session)
|
||||
|
||||
if (href && host.links.open({ href, session: session() })) event.preventDefault()
|
||||
})
|
||||
}
|
||||
|
||||
function webLink(event: MouseEvent, session: () => MountedSession) {
|
||||
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
||||
return
|
||||
const anchor = event.target instanceof Element ? event.target.closest("a[href]") : null
|
||||
|
||||
// `data-pane-row` holds the conversation and the side panels; dialogs and menus render outside it.
|
||||
if (!(anchor instanceof HTMLAnchorElement) || !anchor.closest("[data-pane-row]") || anchor.hasAttribute("download"))
|
||||
return
|
||||
|
||||
return webHref(anchor.getAttribute("href") ?? "", session().server.url)
|
||||
}
|
||||
|
||||
/**
|
||||
* The `CodeBlock` renderers and `CodeBlockAction` buttons for the session's Markdown, by language. Markdown asks only
|
||||
* for complete blocks of a listed language. Content renders inside `Provider` with code block content off, under the
|
||||
|
|
|
|||
11
packages/app/src/runtime/plugin/web-href.test.ts
Normal file
11
packages/app/src/runtime/plugin/web-href.test.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { webHref } from "./web-href"
|
||||
|
||||
test("network-path and explicit web links enter the same session link policy", () => {
|
||||
const base = "https://session.test/base/"
|
||||
expect(webHref("//other.test/path", base)).toBe("https://other.test/path")
|
||||
expect(webHref("http://other.test/path", base)).toBe("http://other.test/path")
|
||||
|
||||
for (const path of ["/api/file", "report.html", "#part", "///etc/x", "//\\host/file", "file:///x"])
|
||||
expect(webHref(path, base)).toBeUndefined()
|
||||
})
|
||||
10
packages/app/src/runtime/plugin/web-href.ts
Normal file
10
packages/app/src/runtime/plugin/web-href.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
/** A web address written in a session, never a relative file, fragment, or UNC path. Desktop renderer origins
|
||||
* need not be HTTP, so use the session server's web scheme for a network-path reference. */
|
||||
export function webHref(written: string, server: string) {
|
||||
const value = written.trim()
|
||||
|
||||
if (!/^(?:https?:\/\/|\/\/)(?![\/\\])/i.test(value) || !URL.canParse(value, server)) return
|
||||
const url = new URL(value, server)
|
||||
|
||||
return /^https?:$/.test(url.protocol) ? url.href : undefined
|
||||
}
|
||||
17
packages/app/src/runtime/server/loopback.test.ts
Normal file
17
packages/app/src/runtime/server/loopback.test.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { sameLoopbackServer } from "./loopback"
|
||||
|
||||
// The window's "local server" and main's "pages share the browser profile" both read this, so they cannot disagree.
|
||||
test.each([
|
||||
{ url: "http://127.0.0.1:4096", own: "http://127.0.0.1:4096", expected: true },
|
||||
{ url: "http://localhost:4096", own: "http://127.0.0.1:4096", expected: true },
|
||||
{ url: "http://[::1]:4096/", own: "http://127.0.0.1:4096", expected: true },
|
||||
// Another loopback port may be a WSL server, a tunnel or a container with its own disk.
|
||||
{ url: "http://localhost:4097", own: "http://127.0.0.1:4096", expected: false },
|
||||
{ url: "https://127.0.0.1:4096", own: "http://127.0.0.1:4096", expected: false },
|
||||
{ url: "http://192.168.1.2:4096", own: "http://127.0.0.1:4096", expected: false },
|
||||
{ url: "http://localhost:4096", own: undefined, expected: false },
|
||||
{ url: "not a url", own: "http://127.0.0.1:4096", expected: false },
|
||||
])("$url is the app's own server at $own: $expected", (row) => {
|
||||
expect(sameLoopbackServer(row.url, row.own)).toBe(row.expected)
|
||||
})
|
||||
22
packages/app/src/runtime/server/loopback.ts
Normal file
22
packages/app/src/runtime/server/loopback.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
/**
|
||||
* A loopback http(s) URL's origin with `localhost`, `127.0.0.1` and `[::1]` read as one host, so two names for the
|
||||
* same port compare equal; undefined for any other URL.
|
||||
*/
|
||||
export function loopbackOrigin(url: string) {
|
||||
if (!URL.canParse(url)) return
|
||||
const parsed = new URL(url)
|
||||
|
||||
if (parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1" && parsed.hostname !== "[::1]") return
|
||||
|
||||
return `${parsed.protocol}//127.0.0.1:${parsed.port || (parsed.protocol === "https:" ? "443" : "80")}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a server URL is the app's own server under any loopback name: the one rule the window (whether a server is
|
||||
* local) and the desktop's main process (whether its pages share the browser profile) both use.
|
||||
*/
|
||||
export function sameLoopbackServer(url: string, own: string | undefined) {
|
||||
const origin = loopbackOrigin(url)
|
||||
|
||||
return !!origin && !!own && origin === loopbackOrigin(own)
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import { batch, createMemo } from "solid-js"
|
|||
import { reconcile, type SetStoreFunction, type Store } from "solid-js/store"
|
||||
import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
import { ServerScope } from "@/runtime/server/scope"
|
||||
import { sameLoopbackServer } from "./loopback"
|
||||
import type { PluginServerStatus } from "./plugin-machine"
|
||||
import { ServerHttp, ServerHttpBase, ServerKey, ServerState } from "./persistence"
|
||||
|
||||
|
|
@ -38,15 +39,6 @@ export function serverLabel(conn: ServerConnection.Any, current?: { hostname?: s
|
|||
return serverName(conn)
|
||||
}
|
||||
|
||||
function loopbackOrigin(url: string) {
|
||||
if (!URL.canParse(url)) return
|
||||
const parsed = new URL(url)
|
||||
|
||||
if (parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1" && parsed.hostname !== "[::1]") return
|
||||
|
||||
return `${parsed.protocol}//127.0.0.1:${parsed.port || (parsed.protocol === "https:" ? "443" : "80")}`
|
||||
}
|
||||
|
||||
// Project data comes from the server; this keeps which projects this client has used and the last one.
|
||||
export function createServerProjects(input: {
|
||||
scope: () => ServerScope
|
||||
|
|
@ -220,10 +212,7 @@ export namespace ServerConnection {
|
|||
|
||||
if (builtin(conn)) return true
|
||||
|
||||
if (conn.type !== "http" || !ownUrl) return false
|
||||
const origin = loopbackOrigin(conn.http.url)
|
||||
|
||||
return !!origin && origin === loopbackOrigin(ownUrl)
|
||||
return conn.type === "http" && sameLoopbackServer(conn.http.url, ownUrl)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ import type { SessionModel } from "@/session/model"
|
|||
import { SESSION_PANEL_WIDTH_MIN } from "@/session/session-panel-width"
|
||||
import { useLayout } from "@/shell/state/layout"
|
||||
import { SessionPanelFrame } from "@/session/session-frame"
|
||||
import { PluginLinks } from "@/runtime/plugin/render"
|
||||
import { createWebLinks, PluginLinks } from "@/runtime/plugin/render"
|
||||
import { createPanelSidebar, createRegion, MobilePanel } from "@/runtime/plugin/panels"
|
||||
import { createMobileViews, MobileViewTabs } from "@/runtime/plugin/mobile"
|
||||
import { usePluginAttachment } from "@/runtime/plugin/host-apis"
|
||||
|
|
@ -54,6 +54,7 @@ import { createPanelMotion, holdLandingWidth, panelOpacity, setPanelResizing } f
|
|||
export function SessionScreenView(props: { session: SessionModel }) {
|
||||
// Link handling for the rest of the screen; each cached timeline provides its own for its session.
|
||||
const mounted = createMountedSession(props.session)
|
||||
createWebLinks(mounted.view)
|
||||
|
||||
return (
|
||||
<PluginLinks session={mounted.view()}>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { clampSessionPanelWidth } from "./session-panel-width"
|
||||
import { clampSessionPanelWidth, fitsSidePane } from "./session-panel-width"
|
||||
|
||||
test("an automatic side pane needs room in the row, excluding the sidebar", () => {
|
||||
expect(fitsSidePane(820 - 240)).toBe(false)
|
||||
expect(fitsSidePane(777)).toBe(false)
|
||||
expect(fitsSidePane(778)).toBe(true)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["keeps widths already within the limit", 800, 1700, false, false, 800],
|
||||
|
|
|
|||
|
|
@ -12,6 +12,10 @@ export const SIDE_PANE_WIDTH_MIN = 320
|
|||
|
||||
const SESSION_PANEL_WIDTH_FIT = 450
|
||||
|
||||
export function fitsSidePane(rowWidth: number) {
|
||||
return rowWidth >= SESSION_PANEL_WIDTH_FIT + SIDE_PANE_WIDTH_MIN + 8
|
||||
}
|
||||
|
||||
const REVIEW_PANE_WIDTH_FIT = 480
|
||||
|
||||
const REVIEW_PANE_WIDTH_FIT_SPLIT = 800
|
||||
|
|
|
|||
|
|
@ -427,6 +427,7 @@ export function TimelineQuote(props: { controller: TimelineQuoteController }) {
|
|||
onCleanup(() => quote.setElement(undefined))
|
||||
}}
|
||||
data-component="timeline-quote"
|
||||
data-floating-overlay
|
||||
data-prevent-autofocus
|
||||
role="toolbar"
|
||||
aria-label={language.t("session.quote.actions")}
|
||||
|
|
|
|||
|
|
@ -143,6 +143,23 @@ test("keys are left alone while keybinds are blocked", () => {
|
|||
expect(ran).toEqual(["palette"])
|
||||
})
|
||||
|
||||
// A page prompt in the browser pane is a modal alert dialog; the app's keys stay off inside it and work everywhere else.
|
||||
test("a modal alert dialog keeps command keys from running inside it", () => {
|
||||
const ran: string[] = []
|
||||
setup([command("palette", "mod+k", ran)])
|
||||
const prompt = document.createElement("div")
|
||||
prompt.setAttribute("role", "alertdialog")
|
||||
prompt.setAttribute("aria-modal", "true")
|
||||
const field = document.createElement("input")
|
||||
prompt.append(field)
|
||||
document.body.append(prompt)
|
||||
|
||||
press(field, { key: "k", ctrlKey: true })
|
||||
press(document.body, { key: "k", ctrlKey: true })
|
||||
|
||||
expect(ran).toEqual(["palette"])
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ keybind: "mod+alt+.", init: { key: "≥", code: "Period", ctrlKey: true, altKey: true } },
|
||||
{ keybind: "mod+shift+[", init: { key: "{", code: "BracketLeft", ctrlKey: true, shiftKey: true } },
|
||||
|
|
|
|||
|
|
@ -208,8 +208,8 @@ function physicalKey(event: Pick<KeyboardEvent, "key" | "code">) {
|
|||
return event.key
|
||||
}
|
||||
|
||||
// The HTML host, except that it drops keys while an IME composes or while command keybinds are blocked, and that
|
||||
// its owner can destroy it, which disposes the keymap.
|
||||
// The HTML host, except that it drops keys while an IME composes, while command keybinds are blocked or while the
|
||||
// keyboard is inside a modal alert dialog, and that its owner can destroy it, which disposes the keymap.
|
||||
function createAppKeymapHost(root: HTMLElement, blocked: () => boolean) {
|
||||
const host = createHtmlKeymapHost(root)
|
||||
const destroyed = new Set<() => void>()
|
||||
|
|
@ -238,6 +238,10 @@ function createAppKeymapHost(root: HTMLElement, blocked: () => boolean) {
|
|||
|
||||
if (blocked()) return
|
||||
|
||||
// A modal alert dialog the app's dialog stack does not track, such as a page's prompt in the browser pane, is
|
||||
// modal for less than the window: its keys are its own.
|
||||
if (original?.target instanceof Element && original.target.closest('[role="alertdialog"][aria-modal="true"]')) return
|
||||
|
||||
listener(event)
|
||||
}),
|
||||
onKeyRelease: (listener) => host.onKeyRelease(listener),
|
||||
|
|
|
|||
|
|
@ -262,6 +262,7 @@ export default function Layout(props: ParentProps) {
|
|||
<div
|
||||
ref={(element) => setState("tabsPanel", element)}
|
||||
data-slot="vertical-tabs-panel"
|
||||
data-floating-overlay={peek.shown() ? "" : undefined}
|
||||
class="absolute inset-0 overflow-clip [contain:layout_style_paint] [overflow-clip-margin:var(--sidebar-divider-bleed,0px)]"
|
||||
classList={{
|
||||
"z-20": organizedSidebar(),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { afterEach, expect, jest, spyOn, test } from "bun:test"
|
||||
import { createRoot, createSignal } from "solid-js"
|
||||
import type { IpcClient, SessionRef, SetupContext } from "@opencode/plugin/gui"
|
||||
import { liveAccessor } from "@opencode/plugin/gui/host"
|
||||
|
|
@ -20,10 +20,31 @@ const tab = (digit: string, url = `https://${digit}.example/`): Browser.Tab => (
|
|||
})
|
||||
|
||||
// The real model over the pane's main-process Ipc, faked at its boundary, with two shell sessions on one server.
|
||||
function fixture() {
|
||||
// `given` is what the window knows of that server, the sessions' location and the pane's Ipc as the model starts.
|
||||
// With `slow`, main takes a registration only once the test calls `answer`, as while it attaches to the server.
|
||||
function fixture(
|
||||
given: { connected?: boolean; compatible?: boolean; local?: boolean; located?: boolean; ipc?: "active" | "pending" | "inactive"; slow?: boolean } = {},
|
||||
) {
|
||||
const bindings = new Map<string, string>()
|
||||
const listeners = new Set<(value: { binding: string; event: PaneEvent }) => void>()
|
||||
const server = { id: "browser-test", compatible: true, builtin: true, data: { on: () => () => undefined } }
|
||||
// What main rejects the next commands with, first in, first out.
|
||||
const rejections: string[] = []
|
||||
const [connected, setConnected] = createSignal(given.connected ?? true)
|
||||
const [ipc, setIpc] = createSignal(given.ipc ?? "active")
|
||||
const answered = Promise.withResolvers<void>()
|
||||
|
||||
if (!given.slow) answered.resolve()
|
||||
|
||||
const server = {
|
||||
id: "browser-test",
|
||||
compatible: given.compatible ?? true,
|
||||
get connected() {
|
||||
return connected()
|
||||
},
|
||||
local: given.local ?? true,
|
||||
builtin: true,
|
||||
data: { on: () => () => undefined, session: { status: () => "idle" } },
|
||||
}
|
||||
|
||||
const refs = ["ses_alpha", "ses_beta"].map((id) => ({
|
||||
key: `${server.id}\n${id}`,
|
||||
|
|
@ -31,7 +52,7 @@ function fixture() {
|
|||
tab: id,
|
||||
server,
|
||||
pending: false,
|
||||
location: { directory: "/repo" },
|
||||
location: given.located === false ? undefined : { directory: "/repo" },
|
||||
}))
|
||||
|
||||
const [current, setCurrent] = createSignal(refs[0])
|
||||
|
|
@ -39,15 +60,21 @@ function fixture() {
|
|||
const pane: PaneClient = {
|
||||
register: async (input) => {
|
||||
bindings.set(input.session, input.binding)
|
||||
await answered.promise
|
||||
},
|
||||
load: async () => undefined,
|
||||
command: async () => undefined,
|
||||
command: async () => {
|
||||
const message = rejections.shift()
|
||||
|
||||
if (message !== undefined) throw new Error(message)
|
||||
},
|
||||
inspect: async () => undefined,
|
||||
highlight: async () => undefined,
|
||||
zoom: async () => undefined,
|
||||
setViewport: async () => undefined,
|
||||
site: async () => ({ cookies: 0 }),
|
||||
clearSite: async () => undefined,
|
||||
reveal: async () => undefined,
|
||||
close: async () => undefined,
|
||||
state: () => undefined,
|
||||
on: (_name, listener) => {
|
||||
|
|
@ -59,17 +86,22 @@ function fixture() {
|
|||
},
|
||||
}
|
||||
|
||||
const live = liveAccessor(() => ({ status: "active" as const, generation: 1, value: pane }))
|
||||
const live = liveAccessor(() => {
|
||||
const status = ipc()
|
||||
|
||||
return status === "active" ? { status, generation: 1, value: pane } : { status }
|
||||
})
|
||||
|
||||
const history = { value: { visits: [] }, set: () => undefined }
|
||||
|
||||
const fake = {
|
||||
id: "browser",
|
||||
t: (key: string) => key,
|
||||
t: (key: string, params?: Record<string, string>) => (params ? `${key} ${JSON.stringify(params)}` : key),
|
||||
use: () => live,
|
||||
sessions: { current, list: () => refs },
|
||||
screen: { current: () => undefined },
|
||||
links: { open: () => undefined },
|
||||
layout: { narrow: () => false, stored: () => [], state: () => "closed", open() {}, close() {} },
|
||||
layout: { narrow: () => false, stored: () => [], state: () => "closed", open() {}, close() {}, side: { opened: () => false } },
|
||||
stores: { history },
|
||||
}
|
||||
|
||||
|
|
@ -78,21 +110,145 @@ function fixture() {
|
|||
const ctx = fake as unknown as SetupContext<typeof definition>
|
||||
const owned = createRoot((dispose) => ({ model: createModel(ctx), dispose }))
|
||||
|
||||
const report = (session: string, event: PaneEvent) => {
|
||||
const send = (session: string, event: PaneEvent) => {
|
||||
const binding = bindings.get(session)
|
||||
|
||||
if (binding) listeners.forEach((listener) => listener({ binding, event }))
|
||||
}
|
||||
|
||||
const emit = (session: string, state: Browser.State) => report(session, { type: "state", state })
|
||||
const emit = (session: string, state: Browser.State) => send(session, { type: "state", state })
|
||||
|
||||
// SAFETY: the model reads only the listed fields of a session ref.
|
||||
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
|
||||
const sessions = refs.map((ref) => ref as unknown as SessionRef)
|
||||
|
||||
return { ...owned, sessions, route: setCurrent, refs, emit, report }
|
||||
return { ...owned, sessions, route: setCurrent, refs, emit, send, rejections, setConnected, setIpc, answer: answered.resolve, registered: () => Array.from(bindings.keys()) }
|
||||
}
|
||||
|
||||
// Runs the promise jobs queued so far, which the fake clock does not: more turns than a registration takes.
|
||||
const turns = async () => {
|
||||
for (const _ of Array.from({ length: 32 })) await Promise.resolve()
|
||||
}
|
||||
|
||||
// Whether the promise is still pending once every queued job ran.
|
||||
const waits = async (promise: Promise<void>) => {
|
||||
const state = { done: false }
|
||||
|
||||
void promise.then(() => (state.done = true))
|
||||
await turns()
|
||||
|
||||
return !state.done
|
||||
}
|
||||
|
||||
afterEach(() => void jest.useRealTimers())
|
||||
|
||||
// What the system says of the network, which nothing but the navigator's own property can change. Returns the undo.
|
||||
const network = (online: boolean) => {
|
||||
const was = navigator.onLine
|
||||
|
||||
Object.defineProperty(navigator, "onLine", { configurable: true, get: () => online })
|
||||
|
||||
return () => void Object.defineProperty(navigator, "onLine", { configurable: true, get: () => was })
|
||||
}
|
||||
|
||||
// A prompt waits for the desktop's attachment only while one is in flight on a server that can answer it. In every
|
||||
// other state the gate resolves in the same tick: no timer runs, and nothing is asked of a server that cannot answer.
|
||||
test.each([
|
||||
{ state: "the server is not connected, or is reconnecting", given: { connected: false } },
|
||||
{ state: "the server is one this app cannot talk to", given: { compatible: false } },
|
||||
{ state: "the session has no location yet", given: { located: false } },
|
||||
{ state: "the window is offline and the server is on another computer", given: { local: false }, offline: true },
|
||||
{ state: "the pane's plugin is disabled or failed", given: { ipc: "inactive" as const } },
|
||||
{ state: "another desktop owns the session", error: "browser.pane.replaced" },
|
||||
{ state: "the server has no browser for the session", error: "browser.pane.unsupported" },
|
||||
{ state: "the server does not have the session", error: "browser.pane.missing" },
|
||||
{ state: "the desktop is attached already", attached: true },
|
||||
{ state: "the plugin was disposed", disposed: true },
|
||||
])("a prompt does not wait when $state", async (row) => {
|
||||
jest.useFakeTimers()
|
||||
const restore = network(!row.offline)
|
||||
const app = fixture(row.given)
|
||||
const session = app.sessions[1]
|
||||
const never = new AbortController().signal
|
||||
|
||||
try {
|
||||
// An earlier prompt met the state: what main answered it with is how the session stands now.
|
||||
if (row.error || row.attached) {
|
||||
const first = app.model.ready(session, never)
|
||||
await turns()
|
||||
app.send(session.id, row.error ? { type: "state", state: null, error: row.error } : { type: "state", state: { tabs: [tab("b")], focusedTabID: tab("b").id } })
|
||||
expect(await waits(first)).toBe(false)
|
||||
}
|
||||
|
||||
if (row.disposed) app.dispose()
|
||||
const registered = app.registered().length
|
||||
expect(await waits(app.model.ready(session, never))).toBe(false)
|
||||
|
||||
// Nothing was started that could not answer.
|
||||
if (!row.attached) expect(app.registered().length).toBe(registered)
|
||||
} finally {
|
||||
restore()
|
||||
app.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ name: "the desktop has attached", end: "answer" },
|
||||
{ name: "the server goes away", end: "disconnect" },
|
||||
{ name: "the plugin is disposed", end: "dispose" },
|
||||
{ name: "the host stops waiting", end: "abort" },
|
||||
{ name: "the pane's plugin stops", end: "ipc" },
|
||||
] as const)("a prompt waits while the attachment is in flight, until $name", async (row) => {
|
||||
jest.useFakeTimers()
|
||||
const app = fixture({ slow: true })
|
||||
const session = app.sessions[1]
|
||||
const host = new AbortController()
|
||||
|
||||
try {
|
||||
const waiting = app.model.ready(session, host.signal)
|
||||
|
||||
expect(await waits(waiting)).toBe(true)
|
||||
expect(app.registered()).toContain(session.id)
|
||||
// No timer of the gate's own ends the wait: the host's does.
|
||||
jest.advanceTimersByTime(900)
|
||||
expect(await waits(waiting)).toBe(true)
|
||||
|
||||
if (row.end === "answer") app.answer()
|
||||
|
||||
if (row.end === "disconnect") app.setConnected(false)
|
||||
|
||||
if (row.end === "dispose") app.dispose()
|
||||
|
||||
if (row.end === "abort") host.abort()
|
||||
|
||||
if (row.end === "ipc") app.setIpc("inactive")
|
||||
expect(await waits(waiting)).toBe(false)
|
||||
} finally {
|
||||
app.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("a prompt waits for a pane that is still starting, and for one whose server is on this computer while offline", async () => {
|
||||
jest.useFakeTimers()
|
||||
const restore = network(false)
|
||||
const starting = fixture({ ipc: "pending" })
|
||||
const local = fixture({ local: true, slow: true })
|
||||
const never = new AbortController().signal
|
||||
|
||||
try {
|
||||
const first = starting.model.ready(starting.sessions[1], never)
|
||||
expect(await waits(first)).toBe(true)
|
||||
starting.setIpc("inactive")
|
||||
expect(await waits(first)).toBe(false)
|
||||
|
||||
expect(await waits(local.model.ready(local.sessions[1], never))).toBe(true)
|
||||
} finally {
|
||||
restore()
|
||||
starting.dispose()
|
||||
local.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("drops page details when a tab closes or its binding is suspended", () => {
|
||||
const app = fixture()
|
||||
|
||||
|
|
@ -107,14 +263,14 @@ test("drops page details when a tab closes or its binding is suspended", () => {
|
|||
try {
|
||||
app.emit(session.id, { tabs: [closed, retained], focusedTabID: closed.id })
|
||||
|
||||
for (const tab of [closed, retained]) app.report(session.id, { type: "page", tabID: tab.id, zoom: 1, viewport })
|
||||
for (const tab of [closed, retained]) app.send(session.id, { type: "page", tabID: tab.id, zoom: 1, viewport })
|
||||
expect(app.model.page(session, closed.id)?.viewport).toEqual(viewport)
|
||||
const remaining = { tabs: [retained], focusedTabID: retained.id }
|
||||
app.emit(session.id, remaining)
|
||||
expect(app.model.page(session, closed.id)).toBeUndefined()
|
||||
expect(app.model.page(session, retained.id)?.viewport).toEqual(viewport)
|
||||
|
||||
app.report(session.id, { type: "state", state: remaining, error: "browser.pane.suspended" })
|
||||
app.send(session.id, { type: "state", state: remaining, error: "browser.pane.suspended" })
|
||||
expect(app.model.tab(session, retained.id)?.url).toBe(retained.url)
|
||||
expect(app.model.page(session, retained.id)).toBeUndefined()
|
||||
} finally {
|
||||
|
|
@ -148,3 +304,132 @@ test("one session's transitions leave another session's attachment as it was", a
|
|||
app.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("the app menu's hard reload runs once, on the pane the window shows", async () => {
|
||||
const app = fixture()
|
||||
const reloads: (boolean | undefined)[] = []
|
||||
const pane = { visible: true }
|
||||
const nothing = () => undefined
|
||||
|
||||
const unmount = app.model.mount({
|
||||
visible: () => pane.visible,
|
||||
address: () => "",
|
||||
reload: (ignoreCache) => void reloads.push(ignoreCache),
|
||||
close: nothing,
|
||||
inspectable: () => false,
|
||||
inspect: nothing,
|
||||
focusAddress: nothing,
|
||||
find: nothing,
|
||||
findMatch: nothing,
|
||||
press: nothing,
|
||||
focused: nothing,
|
||||
})
|
||||
|
||||
try {
|
||||
app.route(app.refs[1])
|
||||
await Bun.sleep(0)
|
||||
// Main sends it to every binding of the window with a tab in front. Only the routed session's pane answers.
|
||||
app.send("ses_alpha", { type: "hardReload" })
|
||||
expect(reloads).toEqual([])
|
||||
app.send("ses_beta", { type: "hardReload" })
|
||||
expect(reloads).toEqual([true])
|
||||
// A pane that is mounted but not on screen, such as behind Review, is not what the person sees.
|
||||
pane.visible = false
|
||||
app.send("ses_beta", { type: "hardReload" })
|
||||
expect(reloads).toEqual([true])
|
||||
} finally {
|
||||
unmount()
|
||||
app.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("a passkey notice names the tab's origin and offers the import for the page's registrable site", async () => {
|
||||
const app = fixture()
|
||||
const [alpha] = app.sessions
|
||||
const page = tab("a", "https://login.github.com/session")
|
||||
|
||||
try {
|
||||
await Bun.sleep(0)
|
||||
app.emit("ses_alpha", { tabs: [page], focusedTabID: page.id })
|
||||
// Main sends both: the notice's own site, which the import searches for, and the origin the tab was on.
|
||||
app.send("ses_alpha", {
|
||||
type: "refusal",
|
||||
tabID: page.id,
|
||||
notice: { reason: "browser.passkey", site: "github.com" },
|
||||
token: "token",
|
||||
site: "https://login.github.com",
|
||||
})
|
||||
expect(app.model.notice(alpha, page.id)).toEqual({
|
||||
token: "token",
|
||||
origin: 'notice.site {"site":"https://login.github.com"}',
|
||||
text: "refused.passkey",
|
||||
label: "refused.passkey.import",
|
||||
passkey: { site: "github.com", choose: true },
|
||||
})
|
||||
// Where the agent's tab refuses, the new tab opens the origin main reported with the notice and the button names
|
||||
// it: not the tab's path, which the page can change without replacing the notice.
|
||||
app.emit("ses_alpha", { tabs: [{ ...page, url: "https://login.github.com/changed?since=notice" }], focusedTabID: page.id })
|
||||
app.send("ses_alpha", { type: "refusal", tabID: page.id, notice: { reason: "browser.passkey.off", site: "github.com" }, token: "off", site: "https://login.github.com" })
|
||||
expect(app.model.notice(alpha, page.id)).toEqual({
|
||||
token: "off",
|
||||
origin: 'notice.site {"site":"https://login.github.com"}',
|
||||
text: "refused.passkey.off",
|
||||
label: "refused.passkey.newTab",
|
||||
title: "https://login.github.com",
|
||||
passkey: { newTab: "https://login.github.com" },
|
||||
})
|
||||
// A page with no web origin has nowhere to reopen.
|
||||
app.send("ses_alpha", { type: "refusal", tabID: page.id, notice: { reason: "browser.passkey.off" }, token: "none" })
|
||||
expect(app.model.notice(alpha, page.id)).toEqual({ token: "none", origin: "notice.page", text: "refused.passkey.off" })
|
||||
} finally {
|
||||
app.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("a command main rejects says what the person tried, never the app's generic failure text", async () => {
|
||||
const app = fixture()
|
||||
const [alpha] = app.sessions
|
||||
const page = tab("a")
|
||||
const warned = spyOn(console, "warn").mockImplementation(() => undefined)
|
||||
|
||||
try {
|
||||
await Bun.sleep(0)
|
||||
app.emit("ses_alpha", { tabs: [page], focusedTabID: page.id })
|
||||
|
||||
// A message main never sent before: the notice names the reload, offers it again, and the code is logged.
|
||||
app.rejections.push("something new in main")
|
||||
app.model.command(alpha, { type: "reload", tabID: page.id })
|
||||
await Bun.sleep(0)
|
||||
expect(app.model.failure(alpha, page.id)).toMatchObject({ text: "failed.command.reload", lasting: false })
|
||||
expect(app.model.failure(alpha, page.id)?.retry).toBeFunction()
|
||||
expect(warned).toHaveBeenCalledWith("[browser] unmapped failure", { code: "something new in main", action: "reload" })
|
||||
// It belongs to the tab the command was for.
|
||||
expect(app.model.failure(alpha, tab("b").id)).toBeUndefined()
|
||||
|
||||
// A refused address keeps main's reason and stays to be read; nothing is logged for a code the table knows.
|
||||
warned.mockClear()
|
||||
app.rejections.push("browser.address.web")
|
||||
app.model.command(alpha, { type: "navigate", tabID: page.id, url: "ftp://files.example/" })
|
||||
await Bun.sleep(0)
|
||||
expect(app.model.failure(alpha, page.id)).toMatchObject({ text: "refused.web", lasting: true, retry: undefined })
|
||||
expect(warned).not.toHaveBeenCalled()
|
||||
|
||||
// A load that failed is the page area's to explain, from the tab's own state: no notice above it as well.
|
||||
app.rejections.push("ERR_NAME_NOT_RESOLVED (-105) loading 'https://nowhere.example/'")
|
||||
app.model.command(alpha, { type: "navigate", tabID: page.id, url: "https://nowhere.example/" })
|
||||
await Bun.sleep(0)
|
||||
expect(app.model.failure(alpha, page.id)).toBeUndefined()
|
||||
|
||||
// The person closes a notice by its identity.
|
||||
app.rejections.push("something new in main")
|
||||
app.model.command(alpha, { type: "back", tabID: page.id })
|
||||
await Bun.sleep(0)
|
||||
const shown = app.model.failure(alpha, page.id)
|
||||
expect(shown?.text).toBe("failed.command.back")
|
||||
app.model.dismissFailure(alpha, shown?.id ?? -1)
|
||||
expect(app.model.failure(alpha, page.id)).toBeUndefined()
|
||||
} finally {
|
||||
warned.mockRestore()
|
||||
app.dispose()
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -282,6 +282,26 @@ function createSync() {
|
|||
}
|
||||
|
||||
const CHILD_PAGE = 200
|
||||
// TODO: `sequence` and SEQUENCE_HANDOFF_MS patch a rare ordering race: a
|
||||
// `!shell` or `/command` sent behind a prompt that waits on a gate (the
|
||||
// desktop browser's attachment) must not reach the server before it. That is
|
||||
// fine for now and needs no core, server or protocol change. `session.prompt`
|
||||
// and `session.compact` already return on durable admission: core's
|
||||
// SessionInbox.admit and admitCompaction publish `session.inbox.enqueued`
|
||||
// (one `session_inbox` row), SessionExecution.wake starts the work, and its
|
||||
// progress arrives as events. `session.shell` and `session.command` do not:
|
||||
// Session.shell joins its fiber until the process exits, publishing
|
||||
// `session.shell.started` and `session.shell.ended` on the way, and
|
||||
// SessionCommand.execute runs the command, whose template may run shell,
|
||||
// before it prompts, so their POST stays open for the whole run. Admitting
|
||||
// both through the inbox, returning on admission and streaming output and
|
||||
// completion as events would make this chain as deterministic as prompt and
|
||||
// compact, and both could then go. The gate exists because the browser
|
||||
// plugin's `attach` RPC needs an existing session; `session.create` already
|
||||
// takes `permissions`, but nothing attaches at creation today.
|
||||
// How long a sequenced request that stays open holds its session's send chain
|
||||
// once it has left: time to reach the server before the next send does.
|
||||
const SEQUENCE_HANDOFF_MS = 250
|
||||
const DELETED_SESSION_LIMIT = 512
|
||||
|
||||
export function createData(config: CreateDataInput) {
|
||||
|
|
@ -453,9 +473,10 @@ export function createData(config: CreateDataInput) {
|
|||
// to exist server-side instead of failing with "not found".
|
||||
const creating = new Map<string, Promise<unknown>>()
|
||||
|
||||
// Per-session send chain: prompts and compactions must be admitted in
|
||||
// submission order. Each waits for the previous POST to settle, so one
|
||||
// failure does not block the next.
|
||||
// Per-session send chain: prompts, compactions and the requests a caller
|
||||
// puts in it with `sequence` must reach the server in submission order.
|
||||
// Each waits for the previous POST to settle, so one failure does not block
|
||||
// the next.
|
||||
const sending = new Map<string, Promise<unknown>>()
|
||||
const messageLoads = new Map<string, Promise<unknown>>()
|
||||
const compacting = new Map<string, { id: string; observed: Set<string>; request: Promise<SessionInboxCompaction> }>()
|
||||
|
|
@ -471,8 +492,14 @@ export function createData(config: CreateDataInput) {
|
|||
void promise.then(settle, settle)
|
||||
}
|
||||
|
||||
// Capture creation before settlement clears its entry, so dependent RPCs still see a failed create.
|
||||
function sendAdmission<Value>(sessionID: string, send: () => Promise<Value>, gate?: Promise<unknown>) {
|
||||
// Capture creation before settlement clears its entry, so dependent RPCs still see a failed create. The chain's
|
||||
// link is the request itself, or `link` of it for a request that stays open after the server has it.
|
||||
function sendAdmission<Value>(
|
||||
sessionID: string,
|
||||
send: () => Promise<Value>,
|
||||
gate?: Promise<unknown>,
|
||||
link?: (request: Promise<Value>) => Promise<unknown>,
|
||||
) {
|
||||
const created = creating.get(sessionID)
|
||||
const previous = sending.get(sessionID)
|
||||
const request = Promise.resolve()
|
||||
|
|
@ -481,7 +508,7 @@ export function createData(config: CreateDataInput) {
|
|||
track(
|
||||
sending,
|
||||
sessionID,
|
||||
request.catch(() => undefined),
|
||||
(link?.(request) ?? request).catch(() => undefined),
|
||||
)
|
||||
return request
|
||||
}
|
||||
|
|
@ -1847,6 +1874,33 @@ export function createData(config: CreateDataInput) {
|
|||
compacting.set(input.sessionID, { id, observed, request })
|
||||
return request
|
||||
},
|
||||
// Runs a session request this layer does not model, such as a shell or a
|
||||
// server command, in the session's send chain: `prepare` and then `send`
|
||||
// start once the prompts, compactions and sequenced requests made before
|
||||
// it have left, so the server receives them in the order they were made.
|
||||
// The chain keeps the order in which requests leave, not the work they
|
||||
// start: such a request can stay open for as long as that work runs, as a
|
||||
// shell command's does until its process exits. Its link therefore ends
|
||||
// when the request settles or has had `SEQUENCE_HANDOFF_MS` to reach the
|
||||
// server, whichever is first.
|
||||
sequence<Value>(sessionID: string, send: () => Promise<Value>, prepare?: () => Promise<unknown>) {
|
||||
const left = Promise.withResolvers<void>()
|
||||
return sendAdmission(
|
||||
sessionID,
|
||||
async () => {
|
||||
await prepare?.()
|
||||
const request = send()
|
||||
left.resolve()
|
||||
return request
|
||||
},
|
||||
undefined,
|
||||
(request) =>
|
||||
Promise.race([
|
||||
request,
|
||||
left.promise.then(() => new Promise((resolve) => setTimeout(resolve, SEQUENCE_HANDOFF_MS))),
|
||||
]),
|
||||
)
|
||||
},
|
||||
// Optimistic prompt admission: render the prompt immediately under a
|
||||
// client-minted ID, send it, and let the durable inbox.enqueued echo
|
||||
// upsert that same ID with the server's payload. Server admission is
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { afterEach, expect, jest, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createData, type CreateDataInput } from "../src/solid"
|
||||
import { OpenCode, type OpenCodeEvent, type SessionInboxItem } from "../src/promise"
|
||||
|
|
@ -133,6 +133,76 @@ test("hydration preserves submission order across optimistic admissions", async
|
|||
}
|
||||
})
|
||||
|
||||
test("a sequenced request leaves only once the prompt made before it has settled, and a failed one does not block the next", async () => {
|
||||
const prepared = Promise.withResolvers<void>()
|
||||
const paths: string[] = []
|
||||
const setup = fixture((request) => {
|
||||
paths.push(new URL(request.url).pathname.split("/").at(-1) ?? "")
|
||||
return Promise.resolve(Response.json({ data: { id: "msg_admitted" } }))
|
||||
})
|
||||
try {
|
||||
// The prompt still prepares, as it does while a plugin readies the session for it.
|
||||
const first = setup.data.session.prompt({ sessionID: item.sessionID, id: "msg_first", text: "First", prepare: () => prepared.promise })
|
||||
const failing = setup.data.session.sequence(item.sessionID, () => Promise.reject(new Error("command failed")))
|
||||
const last = setup.data.session.sequence(item.sessionID, async () => void paths.push("shell"))
|
||||
const failed = failing.catch((error: Error) => error.message)
|
||||
await Bun.sleep(0)
|
||||
expect(paths).toEqual([])
|
||||
|
||||
prepared.resolve()
|
||||
await Promise.all([first, failed, last])
|
||||
expect(paths).toEqual(["prompt", "shell"])
|
||||
expect(await failed).toBe("command failed")
|
||||
} finally {
|
||||
prepared.resolve()
|
||||
setup.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => void jest.useRealTimers())
|
||||
|
||||
test("a sequenced request that stays open holds the next send until it has reached the server, not until it ends", async () => {
|
||||
jest.useFakeTimers()
|
||||
const prepared = Promise.withResolvers<void>()
|
||||
const paths: string[] = []
|
||||
const setup = fixture((request) => {
|
||||
paths.push(new URL(request.url).pathname.split("/").at(-1) ?? "")
|
||||
return Promise.resolve(Response.json({ data: { id: "msg_admitted" } }))
|
||||
})
|
||||
// A shell command's request: the server answers it when the command's process exits.
|
||||
const exited = Promise.withResolvers<void>()
|
||||
const flush = async () => {
|
||||
for (const _ of Array.from({ length: 20 })) await Promise.resolve()
|
||||
}
|
||||
try {
|
||||
const shell = setup.data.session.sequence(
|
||||
item.sessionID,
|
||||
() => (paths.push("shell"), exited.promise),
|
||||
() => prepared.promise,
|
||||
)
|
||||
const prompt = setup.data.session.prompt({ sessionID: item.sessionID, id: "msg_after", text: "After" })
|
||||
// What the shell command waits for before it leaves does not let the prompt overtake it, however long it takes.
|
||||
jest.advanceTimersByTime(60_000)
|
||||
await flush()
|
||||
expect(paths).toEqual([])
|
||||
|
||||
prepared.resolve()
|
||||
await flush()
|
||||
expect(paths).toEqual(["shell"])
|
||||
// The command still runs. The prompt leaves once the command's request has had its moment to arrive.
|
||||
jest.advanceTimersToNextTimer()
|
||||
await prompt
|
||||
expect(paths).toEqual(["shell", "prompt"])
|
||||
|
||||
exited.resolve()
|
||||
await shell
|
||||
} finally {
|
||||
prepared.resolve()
|
||||
exited.resolve()
|
||||
setup.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("hydration coalesces a concurrent optimistic compaction even if its POST fails", async () => {
|
||||
const response = Promise.withResolvers<Response>()
|
||||
const admission = Promise.withResolvers<Response>()
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { statSync } from "node:fs"
|
||||
import { cp, mkdtemp, rm } from "node:fs/promises"
|
||||
import { cp, mkdtemp, realpath, rm } from "node:fs/promises"
|
||||
import { createRequire } from "node:module"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
|
@ -8,6 +8,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"
|
|||
import type { Configuration } from "electron-builder"
|
||||
import { getConfig } from "./electron-builder.config"
|
||||
import { CLI_BINARIES, nodePtyPackage } from "./script/utils"
|
||||
import { verifyPreviewBinding } from "./script/preview-binding"
|
||||
|
||||
// Use electron-builder's matcher so the tests also cover its glob and directory traversal semantics.
|
||||
const { FileMatcher } = createRequire(import.meta.resolve("electron-builder"))("app-builder-lib/out/fileMatcher")
|
||||
|
|
@ -80,6 +81,20 @@ test.each(channels)("channel identity for $channel", ({ channel, appId, feed })
|
|||
expect(config.deb?.fpm).not.toContain("--rpm-rpmbuild-define=_build_id_links none")
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ channel: "dev", inspect: false },
|
||||
{ channel: "beta", inspect: true },
|
||||
{ channel: "prod", inspect: false },
|
||||
])("Electron fuses for $channel", ({ channel, inspect }) => {
|
||||
// Absent keys keep Electron's defaults: NODE_OPTIONS stays on, the asar and file: fuses stay as they are.
|
||||
expect(load(channel).electronFuses).toEqual({
|
||||
enableCookieEncryption: true,
|
||||
runAsNode: false,
|
||||
enableNodeCliInspectArguments: inspect,
|
||||
resetAdHocDarwinSignature: true,
|
||||
})
|
||||
})
|
||||
|
||||
test("legacy Linux launcher stays hidden", async () => {
|
||||
const desktop = await Bun.file(path.join(import.meta.dirname, "resources/linux/opencode-desktop.desktop")).text()
|
||||
expect(desktop).toContain("Exec=/opt/OpenCode/ai.opencode %U")
|
||||
|
|
@ -97,6 +112,7 @@ test.each(channels)("macOS bundle for $channel", ({ channel }) => {
|
|||
|
||||
for (const key of [
|
||||
"NSMicrophoneUsageDescription",
|
||||
"NSCameraUsageDescription",
|
||||
"NSDocumentsFolderUsageDescription",
|
||||
"NSDesktopFolderUsageDescription",
|
||||
"NSDownloadsFolderUsageDescription",
|
||||
|
|
@ -197,6 +213,53 @@ test("trims external dependencies without excluding runtime files", () => {
|
|||
}
|
||||
})
|
||||
|
||||
// The loader finds its binding beside it or, as an isolated install may lay it out, nested under it.
|
||||
test.each([
|
||||
["darwin", "arm64", "darwin-arm64", "beside"], ["darwin", "x64", "darwin-x64", "beside"],
|
||||
["win32", "arm64", "win32-arm64-msvc", "beside"], ["win32", "x64", "win32-x64-msvc", "beside"],
|
||||
["win32", "x64", "win32-x64-msvc", "nested"], ["darwin", "arm64", "darwin-arm64", "nested"],
|
||||
] as const)("packaging %s/%s requires its unpacked preview addon, %s the loader", async (platform, arch, binding, layout) => {
|
||||
const resources = await realpath(await mkdtemp(path.join(os.tmpdir(), "preview-pack-")))
|
||||
const modules = path.join(resources, "app.asar.unpacked/node_modules")
|
||||
const name = `@yuuang/ffi-rs-${binding}`
|
||||
const pkg = path.join(layout === "nested" ? path.join(modules, "ffi-rs/node_modules") : modules, name)
|
||||
const addon = `ffi-rs.${binding}.node`
|
||||
|
||||
try {
|
||||
await Bun.write(path.join(modules, "ffi-rs/package.json"), JSON.stringify({ main: "index.js", optionalDependencies: { [name]: "1.3.7" } }))
|
||||
await Bun.write(path.join(modules, "ffi-rs/index.js"), "module.exports = {}")
|
||||
await Bun.write(path.join(pkg, "package.json"), JSON.stringify({ main: addon, version: "1.3.7" }))
|
||||
|
||||
if (platform === process.platform && arch === process.arch) {
|
||||
const source = createRequire(import.meta.resolve("ffi-rs")).resolve(name)
|
||||
await cp(source, path.join(pkg, addon))
|
||||
await verifyPreviewBinding(resources, platform, arch)
|
||||
// A binding of another version than the loader declares is not the one it was built against.
|
||||
await Bun.write(path.join(pkg, "package.json"), JSON.stringify({ main: addon, version: "1.3.2" }))
|
||||
await expect(verifyPreviewBinding(resources, platform, arch)).rejects.toThrow(addon)
|
||||
await Bun.write(path.join(pkg, "package.json"), JSON.stringify({ main: addon, version: "1.3.7" }))
|
||||
await rm(path.join(pkg, addon))
|
||||
}
|
||||
|
||||
await expect(verifyPreviewBinding(resources, platform, arch)).rejects.toThrow(addon)
|
||||
await Bun.write(path.join(pkg, addon), "not a native library")
|
||||
await expect(verifyPreviewBinding(resources, platform, arch)).rejects.toThrow(addon)
|
||||
} finally {
|
||||
await rm(resources, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
// Linux names an open file through /proc, so a Linux package loads no binding and needs none.
|
||||
test.each(["arm64", "x64"] as const)("packaging linux/%s needs no preview addon", async (arch) => {
|
||||
const resources = await realpath(await mkdtemp(path.join(os.tmpdir(), "preview-pack-")))
|
||||
|
||||
try {
|
||||
await verifyPreviewBinding(resources, "linux", arch)
|
||||
} finally {
|
||||
await rm(resources, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("the trimmed Zip.js package can still export compressed logs", async () => {
|
||||
const config = load("dev")
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "opencode-zip-package-"))
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { Arch, type Configuration } from "electron-builder"
|
|||
import { NativeArch } from "../../script/native-arch"
|
||||
import { DESKTOP_NATIVE_ENGLISH } from "@opencode/app/i18n/desktop-native"
|
||||
import { CLI_BINARIES, getCurrentCli, nodePtyPackage } from "./script/utils"
|
||||
import { previewBinding, verifyPreviewBinding } from "./script/preview-binding"
|
||||
|
||||
const packageDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
|
|
@ -61,6 +62,7 @@ function linuxExecutableName(appId: string): string {
|
|||
|
||||
const getBase = (appId: string): Configuration => {
|
||||
const target = getCurrentCli()
|
||||
const binding = previewBinding(target.os, target.cpu)
|
||||
const desktopName = `${appId}.desktop`
|
||||
|
||||
return {
|
||||
|
|
@ -82,6 +84,7 @@ const getBase = (appId: string): Configuration => {
|
|||
"out/**/*",
|
||||
"resources/**/*",
|
||||
"!resources/opencode-cli*",
|
||||
`!**/node_modules/@yuuang/ffi-rs-!(${binding}){,/**/*}`,
|
||||
// Keep only the target platform's node-pty prebuild when cross-packaging with --cpu=*.
|
||||
...CLI_BINARIES.filter((item) => item.os !== target.os || item.cpu !== target.cpu).map(
|
||||
(item) => `!**/node_modules/@lydell/node-pty-${item.os}-${item.cpu}{,/**/*}`,
|
||||
|
|
@ -101,6 +104,7 @@ const getBase = (appId: string): Configuration => {
|
|||
"!**/node_modules/js-yaml/dist/{js-yaml.js,js-yaml.min.js,*.map}",
|
||||
"!**/node_modules/js-yaml/bin{,/**/*}",
|
||||
],
|
||||
asarUnpack: ["**/node_modules/ffi-rs/**/*", `**/node_modules/@yuuang/ffi-rs-${binding}/**/*`],
|
||||
extraResources: [
|
||||
{
|
||||
from: "resources/",
|
||||
|
|
@ -108,6 +112,23 @@ const getBase = (appId: string): Configuration => {
|
|||
filter: ["opencode-cli", "opencode-cli.exe", "opencode-cli.version"],
|
||||
},
|
||||
],
|
||||
// Electron stores cookies in plain text by default. The browser pane keeps sign-ins, so encrypt them with the OS
|
||||
// key store (Keychain, DPAPI, libsecret or kwallet). This is one-way: turning it off again loses every cookie.
|
||||
// https://www.electronjs.org/docs/latest/tutorial/fuses#cookieencryption
|
||||
// Flipping a fuse breaks the macOS signature. A build without a signing identity is not signed again, so re-sign it
|
||||
// ad hoc or Apple Silicon refuses to launch it. A signed build is signed again after the fuses anyway.
|
||||
electronFuses: {
|
||||
enableCookieEncryption: true,
|
||||
// Started as plain Node (ELECTRON_RUN_AS_NODE) or with an inspector, the signed binary would run any code under
|
||||
// the app's identity, which macOS lets read the app's Keychain key and so every cookie. Nothing runs the app as
|
||||
// Node: the CLI is its own executable. Beta keeps --inspect, as it keeps its on-request debugging port, for the
|
||||
// startup benchmark's Node timings (perf/startup.bench.ts).
|
||||
runAsNode: false,
|
||||
enableNodeCliInspectArguments: resolveChannel() === "beta",
|
||||
// NODE_OPTIONS stays: a packaged app already ignores every option but --http-parser and --max-http-header-size,
|
||||
// and turning the fuse off would also strip NODE_EXTRA_CA_CERTS from the environment the CLI and its terminals get.
|
||||
resetAdHocDarwinSignature: true,
|
||||
},
|
||||
afterPack: async (context) => {
|
||||
const arch = Arch[context.arch]
|
||||
|
||||
|
|
@ -116,6 +137,7 @@ const getBase = (appId: string): Configuration => {
|
|||
|
||||
if (arch !== target.cpu) throw new Error(`Packaging ${arch} Electron with the ${target.target} CLI`)
|
||||
const resources = context.packager.getResourcesDir(context.appOutDir)
|
||||
await verifyPreviewBinding(resources, context.electronPlatformName, arch)
|
||||
const cli = path.join(resources, context.electronPlatformName === "win32" ? "opencode-cli.exe" : "opencode-cli")
|
||||
|
||||
const file = await stat(cli)
|
||||
|
|
@ -161,6 +183,8 @@ const getBase = (appId: string): Configuration => {
|
|||
icon: `resources/icons/icon.icns`,
|
||||
extendInfo: {
|
||||
NSMicrophoneUsageDescription: DESKTOP_NATIVE_ENGLISH["desktop.microphoneUsage"],
|
||||
// Sites in the browser pane may ask for the camera; without this key macOS ends the app when it asks.
|
||||
NSCameraUsageDescription: DESKTOP_NATIVE_ENGLISH["desktop.cameraUsage"],
|
||||
// The CLI server and its terminals run as children of the app, so macOS asks for their access to
|
||||
// these protected locations in the app's name. The prompt shows the description (#56479).
|
||||
NSDocumentsFolderUsageDescription: DESKTOP_NATIVE_ENGLISH["desktop.documentsFolderUsage"],
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@
|
|||
"electron-context-menu": "5.0.0",
|
||||
"electron-log": "^5",
|
||||
"electron-updater": "6.8.9",
|
||||
"ffi-rs": "1.3.7",
|
||||
"lighthouse": "13.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
49
packages/desktop/script/preview-binding.ts
Normal file
49
packages/desktop/script/preview-binding.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { readFile, realpath } from "node:fs/promises"
|
||||
import { createRequire } from "node:module"
|
||||
import path from "node:path"
|
||||
import { Schema } from "effect"
|
||||
import { NativeArch } from "../../../script/native-arch"
|
||||
|
||||
export function previewBinding(platform: string, arch: string) {
|
||||
if (platform === "win32") return `win32-${arch}-msvc`
|
||||
|
||||
if (platform === "linux") return `linux-${arch}-gnu`
|
||||
|
||||
return `${platform}-${arch}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve without executing: a pack host may be building for another OS or CPU. The loader may find its binding beside
|
||||
* it or nested under it, as the install laid them out; either way it is unpacked, the target's, and the version the
|
||||
* loader declares. Linux names an open file through /proc and loads no binding.
|
||||
*/
|
||||
export async function verifyPreviewBinding(resources: string, platform: string, arch: "arm64" | "x64") {
|
||||
if (platform === "linux") return
|
||||
const target = previewBinding(platform, arch)
|
||||
const unpacked = path.join(await realpath(resources), "app.asar.unpacked")
|
||||
const pkg = `@yuuang/ffi-rs-${target}`
|
||||
const addon = `ffi-rs.${target}.node`
|
||||
const inside = (file: string) => file.startsWith(unpacked + path.sep)
|
||||
|
||||
try {
|
||||
const wrapper = createRequire(path.join(unpacked, "out/main/index.js")).resolve("ffi-rs")
|
||||
const binding = createRequire(wrapper).resolve(pkg)
|
||||
const declared = manifest(await readFile(path.join(path.dirname(wrapper), "package.json"), "utf8")).optionalDependencies?.[pkg]
|
||||
const version = manifest(await readFile(path.join(path.dirname(binding), "package.json"), "utf8")).version
|
||||
|
||||
if (!inside(wrapper) || !inside(binding) || path.basename(binding) !== addon || !declared || version !== declared)
|
||||
throw new Error(`Expected the packaged ffi-rs loader to resolve ${pkg}@${declared} to ${addon} inside ${unpacked}, found ${binding}@${version}`)
|
||||
await NativeArch.verify(binding, arch)
|
||||
} catch (cause) {
|
||||
throw new Error(`Invalid unpacked preview binding for ${target}: ${addon} (${cause instanceof Error ? cause.message : cause})`, { cause })
|
||||
}
|
||||
}
|
||||
|
||||
const manifest = Schema.decodeUnknownSync(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
version: Schema.optional(Schema.String),
|
||||
optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { remoteDebuggingPort } from "./options"
|
||||
import { debuggingSwitches, remoteDebuggingPort } from "./options"
|
||||
|
||||
const builds = {
|
||||
dev: { packaged: false, channel: "dev" },
|
||||
|
|
@ -8,6 +8,12 @@ const builds = {
|
|||
packagedDev: { packaged: true, channel: "dev" },
|
||||
}
|
||||
|
||||
test.each([
|
||||
["dev", "9222", true], ["beta", "0", true], ["packagedDev", undefined, false], ["stable", undefined, false],
|
||||
] as const)("%s applies its policy to explicit Chromium launch switches too", (build, port, pipe) => {
|
||||
expect(debuggingSwitches(builds[build], undefined, "0", true)).toEqual({ port, pipe })
|
||||
})
|
||||
|
||||
test.each([
|
||||
["dev", undefined, "9222"],
|
||||
["dev", "9333", "9333"],
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
import { debugBuild } from "@opencode/gui-plugins/debug/options"
|
||||
|
||||
export function debuggingSwitches(build: { packaged: boolean; channel: string }, env: string | undefined, port: string | undefined, pipe: boolean) {
|
||||
if (!debugBuild(build)) return { port: undefined, pipe: false }
|
||||
|
||||
return { port: remoteDebuggingPort(build, env) ?? port, pipe }
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote debugging port, only in debug builds. The dev server opens 9222 unless told otherwise; Beta opens one only
|
||||
* when `OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT` names it. `0` lets Chromium pick a free port.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
import { describe, expect, test } from "bun:test"
|
||||
import { resolve } from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { resolveExternalURL, resolveLocalFilePath } from "./external-url"
|
||||
import { resolveExternalURL } from "./external-url"
|
||||
|
||||
describe("external URLs", () => {
|
||||
test("opens only web and mail URLs externally", () => {
|
||||
|
|
@ -13,10 +11,4 @@ describe("external URLs", () => {
|
|||
expect(resolveExternalURL(url)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("resolves only local file URLs", () => {
|
||||
const path = resolve("example.html")
|
||||
expect(resolveLocalFilePath(pathToFileURL(path).href)).toBe(path)
|
||||
expect(resolveLocalFilePath("file://example.com/share/index.html")).toBeUndefined()
|
||||
expect(resolveLocalFilePath("https://example.com/index.html")).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
import { fileURLToPath } from "node:url"
|
||||
|
||||
export function resolveExternalURL(value: string) {
|
||||
if (!URL.canParse(value)) return undefined
|
||||
const url = new URL(value)
|
||||
|
|
@ -8,16 +6,3 @@ export function resolveExternalURL(value: string) {
|
|||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function resolveLocalFilePath(value: string) {
|
||||
if (!URL.canParse(value)) return undefined
|
||||
const url = new URL(value)
|
||||
|
||||
if (url.protocol !== "file:" || url.hostname) return undefined
|
||||
|
||||
try {
|
||||
return fileURLToPath(url)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
export * as DesktopFiles from "./index"
|
||||
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { clipboard, dialog, nativeImage, shell, webContents } from "electron"
|
||||
import { app, clipboard, dialog, nativeImage, shell, webContents } from "electron"
|
||||
import { Context, Effect, FileSystem, Layer, Path } from "effect"
|
||||
import type { DirectoryPickerOptions, FilePickerOptions, SaveFilePickerOptions } from "../../shared/ipc-contract"
|
||||
import { scoped } from "../native/logging"
|
||||
import { nativeT } from "../native/translations"
|
||||
import { assertAttachmentBudget, createPickedFileAuthorizations, readAttachment } from "./attachment-picker"
|
||||
import { resolveExternalURL, resolveLocalFilePath } from "./external-url"
|
||||
import { resolveExternalURL } from "./external-url"
|
||||
import { pickerStarts } from "./picker-start"
|
||||
|
||||
export type Interface = ReturnType<typeof make>
|
||||
|
||||
|
|
@ -59,13 +60,24 @@ function make(
|
|||
path: Path.Path,
|
||||
pickedFiles: ReturnType<typeof createPickedFileAuthorizations>,
|
||||
) {
|
||||
// The first start that exists; none when even home is gone, which leaves the system to choose.
|
||||
const start = Effect.fnUntraced(function* (requested: string | undefined, save = false) {
|
||||
for (const candidate of pickerStarts(requested, app.getPath("home"), save)) {
|
||||
if (yield* fs.exists(candidate.check).pipe(Effect.orElseSucceed(() => false))) return candidate.use
|
||||
}
|
||||
|
||||
return undefined
|
||||
})
|
||||
|
||||
return {
|
||||
openDirectoryPicker: Effect.fn("DesktopFiles.openDirectoryPicker")(function* (options?: DirectoryPickerOptions) {
|
||||
const defaultPath = yield* start(options?.defaultPath)
|
||||
|
||||
const result = yield* Effect.promise(() =>
|
||||
dialog.showOpenDialog({
|
||||
properties: ["openDirectory", ...(options?.multiple ? ["multiSelections" as const] : []), "createDirectory"],
|
||||
title: options?.title ?? nativeT("desktop.dialog.chooseFolder"),
|
||||
defaultPath: options?.defaultPath,
|
||||
defaultPath,
|
||||
}),
|
||||
)
|
||||
|
||||
|
|
@ -79,11 +91,13 @@ function make(
|
|||
if (picker === undefined) return null
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const defaultPath = yield* start(options?.defaultPath)
|
||||
|
||||
const result = yield* Effect.promise(() =>
|
||||
dialog.showOpenDialog({
|
||||
properties: ["openFile", ...(options?.multiple ? ["multiSelections" as const] : [])],
|
||||
title: options?.title ?? nativeT("desktop.dialog.chooseFile"),
|
||||
defaultPath: options?.defaultPath,
|
||||
defaultPath,
|
||||
filters: pickerFilters(options?.extensions),
|
||||
}),
|
||||
)
|
||||
|
|
@ -109,10 +123,12 @@ function make(
|
|||
readPickedFile: pickedFiles.read,
|
||||
releasePickedFiles: pickedFiles.release,
|
||||
saveFile: Effect.fn("DesktopFiles.saveFile")(function* (options: SaveFilePickerOptions, content: string) {
|
||||
const defaultPath = yield* start(options?.defaultPath, true)
|
||||
|
||||
const result = yield* Effect.promise(() =>
|
||||
dialog.showSaveDialog({
|
||||
title: options?.title ?? nativeT("desktop.dialog.saveFile"),
|
||||
defaultPath: options?.defaultPath,
|
||||
defaultPath,
|
||||
}),
|
||||
)
|
||||
|
||||
|
|
@ -217,20 +233,6 @@ export const openExternalURL = Effect.fn("DesktopFiles.openExternalURL")(functio
|
|||
)
|
||||
})
|
||||
|
||||
export const openLocalFileURL = Effect.fn("DesktopFiles.openLocalFileURL")(function* (value: string) {
|
||||
const path = resolveLocalFilePath(value)
|
||||
|
||||
if (!path) {
|
||||
yield* scoped("window", Effect.logWarning("blocked local file target", { url: value }))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const error = yield* Effect.promise(() => shell.openPath(path))
|
||||
|
||||
if (error) yield* scoped("window", Effect.logError("failed to open local file", { path, error }))
|
||||
})
|
||||
|
||||
function pickerFilters(extensions?: string[]) {
|
||||
if (!extensions?.length) return undefined
|
||||
|
||||
|
|
|
|||
48
packages/desktop/src/main/files/picker-start.test.ts
Normal file
48
packages/desktop/src/main/files/picker-start.test.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import path from "node:path"
|
||||
import { pickerStarts } from "./picker-start"
|
||||
|
||||
const home = path.resolve("home", "me")
|
||||
|
||||
const project = path.resolve("work", "project")
|
||||
|
||||
test.each([
|
||||
{
|
||||
name: "no request opens at home, never the system's default",
|
||||
requested: undefined,
|
||||
save: false,
|
||||
starts: [{ check: home, use: home }],
|
||||
},
|
||||
{
|
||||
name: "a blank request is no folder",
|
||||
requested: " ",
|
||||
save: false,
|
||||
starts: [{ check: home, use: home }],
|
||||
},
|
||||
{
|
||||
name: "a relative request is no folder",
|
||||
requested: path.join("relative", "folder"),
|
||||
save: false,
|
||||
starts: [{ check: home, use: home }],
|
||||
},
|
||||
{
|
||||
name: "an explicit folder is tried first, then home",
|
||||
requested: project,
|
||||
save: false,
|
||||
starts: [
|
||||
{ check: project, use: project },
|
||||
{ check: home, use: home },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "a save picker checks the suggested file's folder and keeps its name at home",
|
||||
requested: path.join(project, "notes.txt"),
|
||||
save: true,
|
||||
starts: [
|
||||
{ check: project, use: path.join(project, "notes.txt") },
|
||||
{ check: home, use: path.join(home, "notes.txt") },
|
||||
],
|
||||
},
|
||||
])("$name", ({ requested, save, starts }) => {
|
||||
expect(pickerStarts(requested, home, save)).toEqual(starts)
|
||||
})
|
||||
16
packages/desktop/src/main/files/picker-start.ts
Normal file
16
packages/desktop/src/main/files/picker-start.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import path from "node:path"
|
||||
|
||||
/**
|
||||
* Where a native picker may open, best first: `check` must exist for `use` to be passed as its default path. Without
|
||||
* one, Windows opens at the Desktop, and shows "Location is not available" before the picker when that folder is
|
||||
* missing or redirected away; a folder that exists always opens cleanly. A save picker keeps the suggested file name
|
||||
* in whichever folder it opens. A relative request names no folder and is ignored.
|
||||
*/
|
||||
export function pickerStarts(requested: string | undefined, home: string, save: boolean) {
|
||||
const named = requested?.trim() && path.isAbsolute(requested) ? requested : undefined
|
||||
|
||||
return [
|
||||
...(named ? [{ check: save ? path.dirname(named) : named, use: named }] : []),
|
||||
{ check: home, use: save && named ? path.join(home, path.basename(named)) : home },
|
||||
]
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { Effect } from "effect"
|
||||
import { FileRpcs } from "../../shared/ipc-rpc"
|
||||
import { DesktopFiles, openExternalURL, openLocalFileURL } from "../files"
|
||||
import { DesktopFiles, openExternalURL } from "../files"
|
||||
import { IpcPortHandoff } from "../ipc-transport"
|
||||
import { sender } from "./context"
|
||||
|
||||
|
|
@ -27,7 +27,6 @@ export const fileHandlers = FileRpcs.toLayer(
|
|||
FilesSaveFile: ({ options, content }) => files.saveFile(options, content).pipe(Effect.orDie),
|
||||
FilesOpenExternal: ({ url }) => openExternalURL(url).pipe(Effect.asVoid),
|
||||
FilesOpenBrowser: ({ url }) => (/^https?:/i.test(url) ? openExternalURL(url) : Effect.succeed(false)),
|
||||
FilesOpenLocalFile: ({ url }) => openLocalFileURL(url),
|
||||
FilesOpenPath: ({ path, application }) =>
|
||||
files.openPath(path, application).pipe(
|
||||
Effect.map((result) => result ?? null),
|
||||
|
|
|
|||
|
|
@ -125,15 +125,15 @@ describe("desktop RPC transport", () => {
|
|||
const handoff = await runtime.runPromise(IpcPortHandoff)
|
||||
const win = sender(1)
|
||||
// A window that has not asked for its snapshot has no document to hold events for.
|
||||
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "early" }))).toBe(false)
|
||||
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "early", accelerator: false }))).toBe(false)
|
||||
|
||||
handoff.prepare(win)
|
||||
// On dev these were dropped: the window had no event queue until its port bound.
|
||||
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "a" }))).toBe(true)
|
||||
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "b" }))).toBe(true)
|
||||
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "a", accelerator: false }))).toBe(true)
|
||||
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "b", accelerator: false }))).toBe(true)
|
||||
const channel = new MessageChannel()
|
||||
handoff.bind(win, serverPort(channel.port1))
|
||||
emitIpcEvent(win, new MenuCommandTriggered({ id: "c" }))
|
||||
emitIpcEvent(win, new MenuCommandTriggered({ id: "c", accelerator: false }))
|
||||
|
||||
expect(await chunks(channel.port2, 0, "DesktopEvents", 3)).toEqual(["a", "b", "c"].map(menuCommand))
|
||||
|
||||
|
|
@ -156,7 +156,7 @@ describe("desktop RPC transport", () => {
|
|||
// The new document's snapshot: the old one stops receiving events but still answers its RPCs.
|
||||
handoff.prepare(win)
|
||||
expect((await firstEvents).chunks).toEqual([])
|
||||
emitIpcEvent(win, new MenuCommandTriggered({ id: "during reload" }))
|
||||
emitIpcEvent(win, new MenuCommandTriggered({ id: "during reload", accelerator: false }))
|
||||
Effect.runSync(Deferred.succeed(flushGate, undefined))
|
||||
expect((await flush).exit).toEqual(success("flushed"))
|
||||
|
||||
|
|
@ -187,7 +187,7 @@ const eventsLive = RpcServer.layer(EventRpcs.merge(FlushRpcs)).pipe(
|
|||
)
|
||||
|
||||
function menuCommand(id: string) {
|
||||
return Schema.encodeSync(MenuCommandTriggered)(new MenuCommandTriggered({ id }))
|
||||
return Schema.encodeSync(MenuCommandTriggered)(new MenuCommandTriggered({ id, accelerator: false }))
|
||||
}
|
||||
|
||||
class TestEvent extends Schema.TaggedClass<TestEvent>()("TestEvent", { value: Schema.String }) {}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import { DesktopCli } from "./service/desktop-cli"
|
|||
import { setStorageSnapshotObserver } from "./storage/snapshot"
|
||||
import { getLastFocusedWindow } from "./windows"
|
||||
import { isRendererUrl } from "./windows/scheme"
|
||||
import { receivesPluginPort } from "./windows/security"
|
||||
|
||||
const services = Layer.mergeAll(DesktopFiles.layer, Plugins.layer)
|
||||
|
||||
|
|
@ -68,8 +69,9 @@ export const registerIpcHandlers = Effect.gen(function* () {
|
|||
win.webContents.send(DragCancelEvent)
|
||||
})
|
||||
|
||||
// The check on each call (`caller` in ipc-handlers/plugins.ts) then names the window this document belongs to.
|
||||
const post = () => {
|
||||
if (win.isDestroyed() || win.webContents.isDestroyed()) return
|
||||
if (!receivesPluginPort(win)) return
|
||||
const channel = new MessageChannelMain()
|
||||
handoff.bind(win.webContents, channel.port1)
|
||||
win.webContents.postMessage(IpcTransportPort, null, [channel.port2])
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import path from "node:path"
|
|||
import { app } from "electron"
|
||||
import { debugBuild, memoryLogInterval } from "@opencode/gui-plugins/debug/options"
|
||||
import { APP_ID, APP_NAME, CHANNEL } from "../constants"
|
||||
import { remoteDebuggingPort } from "../diagnostics/options"
|
||||
import { debuggingSwitches } from "../diagnostics/options"
|
||||
|
||||
const testOnboarding = process.env.OPENCODE_TEST_ONBOARDING === "1"
|
||||
|
||||
|
|
@ -32,12 +32,19 @@ export function configureApplication() {
|
|||
if (process.platform === "linux") app.commandLine.appendSwitch("disable-smooth-scrolling")
|
||||
|
||||
const build = { packaged: app.isPackaged, channel: CHANNEL }
|
||||
const debugPort = remoteDebuggingPort(build, process.env.OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT)
|
||||
|
||||
if (debugPort) app.commandLine.appendSwitch("remote-debugging-port", debugPort)
|
||||
const debug = debuggingSwitches(build, process.env.OPENCODE_DESKTOP_REMOTE_DEBUGGING_PORT,
|
||||
app.commandLine.hasSwitch("remote-debugging-port") ? app.commandLine.getSwitchValue("remote-debugging-port") : undefined,
|
||||
app.commandLine.hasSwitch("remote-debugging-pipe"))
|
||||
|
||||
if (app.commandLine.hasSwitch("remote-debugging-port"))
|
||||
for (const name of ["remote-debugging-port", "remote-debugging-pipe", "remote-debugging-address"]) app.commandLine.removeSwitch(name)
|
||||
|
||||
if (debug.pipe) app.commandLine.appendSwitch("remote-debugging-pipe")
|
||||
|
||||
if (debug.port !== undefined) {
|
||||
app.commandLine.appendSwitch("remote-debugging-port", debug.port)
|
||||
app.commandLine.appendSwitch("remote-debugging-address", "127.0.0.1")
|
||||
}
|
||||
|
||||
// Precise heap sizes need a launch switch. The debug bar's toggle starts the log without one.
|
||||
if (debugBuild(build) && memoryLogInterval(process.env.OPENCODE_DESKTOP_MEMORY_LOG) !== undefined)
|
||||
|
|
|
|||
|
|
@ -96,8 +96,8 @@ function build(deps: Deps, provider: MenubarProvider) {
|
|||
Menu.setApplicationMenu(built)
|
||||
}
|
||||
|
||||
export function sendMenuCommand(win: BrowserWindow, id: string) {
|
||||
emitIpcEvent(win.webContents, new MenuCommandTriggered({ id }))
|
||||
export function sendMenuCommand(win: BrowserWindow, id: string, accelerator: boolean) {
|
||||
emitIpcEvent(win.webContents, new MenuCommandTriggered({ id, accelerator }))
|
||||
}
|
||||
|
||||
function nativeMenu(menu: DesktopMenu, extra: readonly MenubarEntry[], deps: Deps): MenuItemConstructorOptions {
|
||||
|
|
@ -145,10 +145,10 @@ function nativeItem(entry: DesktopMenuEntry, deps: Deps): MenuItemConstructorOpt
|
|||
if (entry.command) {
|
||||
const command = entry.command
|
||||
|
||||
item.click = () => {
|
||||
item.click = (_item, _window, event) => {
|
||||
const win = deps.commandWindow()
|
||||
|
||||
if (win) sendMenuCommand(win, command)
|
||||
if (win) sendMenuCommand(win, command, !!event.triggeredByAccelerator)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { app, BrowserWindow } from "electron"
|
||||
import { sameLoopbackServer } from "@opencode/app/loopback"
|
||||
import { builtins } from "@opencode/gui-plugins/main"
|
||||
import {
|
||||
pluginIdAvailable,
|
||||
|
|
@ -329,7 +330,8 @@ export function createHost(input: {
|
|||
id,
|
||||
url: endpoint.url,
|
||||
headers: authorization ? { authorization } : {},
|
||||
sameMachine: !!sidecar && URL.canParse(endpoint.url) && new URL(endpoint.url).origin === sidecar.url,
|
||||
// The window's rule for a local server, so the pane offers extensions exactly where pages share the profile.
|
||||
sameMachine: sameLoopbackServer(endpoint.url, sidecar?.url),
|
||||
password: endpoint.password,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import electron, { type BrowserWindow } from "electron"
|
||||
import { schemes } from "@opencode/gui-plugins/schemes"
|
||||
|
||||
export const rendererProtocol = "oc"
|
||||
|
||||
|
|
@ -34,6 +35,7 @@ export function isRendererUrl(value?: string, html = false) {
|
|||
// before it loads anything else.
|
||||
export function registerRendererScheme() {
|
||||
electron.protocol.registerSchemesAsPrivileged([
|
||||
...schemes,
|
||||
{
|
||||
scheme: rendererProtocol,
|
||||
privileges: {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { EventEmitter } from "node:events"
|
||||
import type { BrowserWindow, Session, WebContents } from "electron"
|
||||
import { allowRendererPermissions } from "./security"
|
||||
import { allowRendererPermissions, receivesPluginPort } from "./security"
|
||||
|
||||
type RequestHandler = NonNullable<Parameters<Session["setPermissionRequestHandler"]>[0]>
|
||||
|
||||
|
|
@ -121,3 +121,20 @@ test("retains permissions across all live windows on a shared session and revoke
|
|||
expect(await shared.ask(1, "notifications")).toBe(false)
|
||||
expect(shared.check(null, "notifications", { isMainFrame: false })).toBe(false)
|
||||
})
|
||||
|
||||
test("hands the plugin port only to the app's own document, never to a page the window went to", () => {
|
||||
const window = (url: string, destroyed = false) => ({
|
||||
isDestroyed: () => destroyed,
|
||||
webContents: { isDestroyed: () => false, mainFrame: { url } },
|
||||
})
|
||||
|
||||
expect(receivesPluginPort(window(url))).toBe(true)
|
||||
expect(receivesPluginPort(window("oc://renderer/settings.html#/browser"))).toBe(true)
|
||||
// A web page, a preview, another host on the app's scheme and an address that only looks like the app's.
|
||||
expect(receivesPluginPort(window("https://evil.test/"))).toBe(false)
|
||||
expect(receivesPluginPort(window("oc-preview://file/index.html"))).toBe(false)
|
||||
expect(receivesPluginPort(window("oc://evil/index.html"))).toBe(false)
|
||||
expect(receivesPluginPort(window("https://renderer.evil.test/oc://renderer/index.html"))).toBe(false)
|
||||
expect(receivesPluginPort(window(""))).toBe(false)
|
||||
expect(receivesPluginPort(window(url, true))).toBe(false)
|
||||
})
|
||||
|
|
@ -71,6 +71,14 @@ function registerPermissionHandlers(session: Session) {
|
|||
return allowed
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the window's document may receive the plugin port. A port carries no sender frame, so only the app's own
|
||||
* document may: a page the window was navigated to, or a document of another origin, gets none.
|
||||
*/
|
||||
export function receivesPluginPort(win: { isDestroyed(): boolean; webContents: { isDestroyed(): boolean; mainFrame: { url: string } } }) {
|
||||
return !win.isDestroyed() && !win.webContents.isDestroyed() && isRendererUrl(win.webContents.mainFrame.url)
|
||||
}
|
||||
|
||||
export function wireNavigationPolicy(win: BrowserWindow, openExternalURL: (url: string) => void) {
|
||||
win.webContents.setWindowOpenHandler(({ url }) => {
|
||||
if (!isRendererUrl(url)) openExternalURL(url)
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export type ElectronAPI = {
|
|||
getWindowID(): string
|
||||
getWindowBootstrap(): WindowBootstrap
|
||||
themeReady(): Promise<void>
|
||||
onMenuCommand(cb: (id: string) => void): () => void
|
||||
onMenuCommand(cb: (id: string, accelerator: boolean) => void): () => void
|
||||
onDeepLink(cb: (delivery: { attempt: number; urls: string[] }) => void): () => void
|
||||
openDirectoryPicker(opts?: DirectoryPickerOptions): Promise<string | string[] | null>
|
||||
openFilePicker(opts?: FilePickerOptions): Promise<PickedFiles | null>
|
||||
|
|
@ -49,7 +49,6 @@ export type ElectronAPI = {
|
|||
saveFile(opts: SaveFilePickerOptions, content: string): Promise<boolean>
|
||||
openExternal(url: string): void
|
||||
openBrowser(url: string): Promise<boolean>
|
||||
openLocalFile(url: string): void
|
||||
openPath(path: string, app?: string): Promise<string | undefined>
|
||||
revealPath(path: string): Promise<boolean>
|
||||
readClipboardImage(): Promise<ClipboardImage | null>
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ export const api: ElectronAPI = {
|
|||
getWindowID: () => window.electron.windowID,
|
||||
getWindowBootstrap: () => window.electron.bootstrap,
|
||||
themeReady: () => invoke("WindowThemeReady"),
|
||||
onMenuCommand: (cb) => listen("MenuCommandTriggered", (event) => cb(event.id)),
|
||||
onMenuCommand: (cb) => listen("MenuCommandTriggered", (event) => cb(event.id, event.accelerator)),
|
||||
onDeepLink: (cb) => listen("DeepLinksOpened", (event) => cb({ attempt: event.attempt, urls: mutable(event.urls) })),
|
||||
|
||||
openDirectoryPicker: (opts) => invoke("FilesOpenDirectoryPicker", { options: opts }).then(mutable),
|
||||
|
|
@ -54,7 +54,6 @@ export const api: ElectronAPI = {
|
|||
saveFile: (opts, content) => invoke("FilesSaveFile", { options: opts, content }),
|
||||
openExternal: (url) => send("FilesOpenExternal", { url }),
|
||||
openBrowser: (url) => invoke("FilesOpenBrowser", { url }),
|
||||
openLocalFile: (url) => send("FilesOpenLocalFile", { url }),
|
||||
openPath: (path, app) => invoke("FilesOpenPath", { path, application: app }).then((value) => value ?? undefined),
|
||||
revealPath: (path) => invoke("FilesRevealPath", { path }),
|
||||
readClipboardImage: () =>
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ function fileApi(events: string[]): Parameters<typeof createDesktopFiles>[0] {
|
|||
saveFile: async () => false,
|
||||
openExternal: () => {},
|
||||
openBrowser: async () => true,
|
||||
openLocalFile: () => {},
|
||||
resolveAppPath: async () => null,
|
||||
openPath: async () => undefined,
|
||||
revealPath: async () => false,
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ type DesktopFileAPI = Pick<
|
|||
| "saveFile"
|
||||
| "openExternal"
|
||||
| "openBrowser"
|
||||
| "openLocalFile"
|
||||
| "resolveAppPath"
|
||||
| "openPath"
|
||||
| "revealPath"
|
||||
|
|
@ -77,7 +76,6 @@ export function createDesktopFiles(api: DesktopFileAPI, os: DesktopOS) {
|
|||
api.saveFile({ title: options.title, defaultPath: options.defaultPath }, content),
|
||||
openExternal: (url: string) => api.openExternal(url),
|
||||
openBrowser: (url: string) => api.openBrowser(url),
|
||||
openLocalFile: (url: string) => api.openLocalFile(url),
|
||||
async openPath(path: string, app?: string) {
|
||||
if (os !== "windows") {
|
||||
await api.openPath(path, app)
|
||||
|
|
|
|||
|
|
@ -23,9 +23,17 @@ function dispatch(event: MenuRouterEvent) {
|
|||
)
|
||||
}
|
||||
|
||||
/** Commands that arrive before the app interface binds run once it does. */
|
||||
/**
|
||||
* Commands that arrive before the app interface binds run once it does. A key equivalent the page left unhandled runs
|
||||
* nothing while the keyboard is in a modal alert dialog, such as a page's prompt: macOS offers the menu every key the
|
||||
* focused element does not consume, as Control+` or Option+Down on a prompt's button.
|
||||
*/
|
||||
export function startDesktopMenu(api: ElectronAPI) {
|
||||
api.onMenuCommand((id) => dispatch({ type: "command.received", id }))
|
||||
api.onMenuCommand((id, accelerator) => {
|
||||
// A minimized or unfocused window keeps its active element: only a window with the keyboard drops the command.
|
||||
if (accelerator && document.hasFocus() && document.activeElement?.closest('[role="alertdialog"][aria-modal="true"]')) return
|
||||
dispatch({ type: "command.received", id })
|
||||
})
|
||||
}
|
||||
|
||||
/** Routes menu commands to `handler` until the returned function unbinds it. */
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ export class DeepLinksOpened extends Schema.TaggedClass<DeepLinksOpened>()("Deep
|
|||
|
||||
export class MenuCommandTriggered extends Schema.TaggedClass<MenuCommandTriggered>()("MenuCommandTriggered", {
|
||||
id: Schema.String,
|
||||
/** A key equivalent chose the item, rather than a click on the menu. */
|
||||
accelerator: Schema.Boolean,
|
||||
}) {}
|
||||
|
||||
export class WindowFullscreenChanged extends Schema.TaggedClass<WindowFullscreenChanged>()("WindowFullscreenChanged", {
|
||||
|
|
|
|||
|
|
@ -59,10 +59,6 @@ export const FilesOpenBrowser = Rpc.make("FilesOpenBrowser", {
|
|||
success: Schema.Boolean,
|
||||
})
|
||||
|
||||
export const FilesOpenLocalFile = Rpc.make("FilesOpenLocalFile", {
|
||||
payload: { url: Schema.String },
|
||||
})
|
||||
|
||||
export const FilesOpenPath = Rpc.make("FilesOpenPath", {
|
||||
payload: { path: Schema.String, application: Schema.optional(Schema.String) },
|
||||
success: Schema.NullOr(Schema.String),
|
||||
|
|
@ -89,7 +85,6 @@ export const FileRpcs = RpcGroup.make(
|
|||
FilesSaveFile,
|
||||
FilesOpenExternal,
|
||||
FilesOpenBrowser,
|
||||
FilesOpenLocalFile,
|
||||
FilesOpenPath,
|
||||
FilesRevealPath,
|
||||
FilesReadClipboardImage,
|
||||
|
|
|
|||
|
|
@ -5,11 +5,12 @@ Built-in features of the desktop and web app, each behind the GUI plugin SDK, `@
|
|||
## Structure
|
||||
|
||||
- The SDK and the contracts `file`, `review`, `browser` and `updater` live in `packages/plugin/src/gui/`; all but `updater` publish with `@opencode/plugin` as `@opencode/plugin/gui*`. Built-ins, hosts and third-party plugin bundles all import them by that name; this package holds only the built-ins. Three subpaths are workspace-only and never published: `gui/host` (the hosts' protocol), `gui/builtin` (what only built-ins use) and `gui/updater` (the app's own updater contract).
|
||||
- Keep the public SDK for third-party plugins. API only built-ins use goes in `@opencode/plugin/gui/builtin` (`packages/plugin/src/gui/builtin.ts`), which no public SDK module imports: import `onIdle`, `BuiltinStore`, `BuiltinPanel`, `BuiltinPanelTab`, `BuiltinCommand`, `BuiltinSlot`, `builtinContext`, `builtinMainContext` and `builtinCatalog` from there. Each built-in registry token has the public token's id; the hosts read every item through it.
|
||||
- Keep the public SDK for third-party plugins. API only built-ins use goes in `@opencode/plugin/gui/builtin` (`packages/plugin/src/gui/builtin.ts`), which no public SDK module imports: import `onIdle`, `BuiltinStore`, `BuiltinPanel`, `BuiltinPanelTab`, `BuiltinCommand`, `BuiltinAppLink`, `BuiltinPromptGate`, `BuiltinSlot`, `builtinContext`, `builtinMainContext` and `builtinCatalog` from there. Each built-in registry token has the public token's id; the hosts read every item through it.
|
||||
- Built-ins declare with `Plugin.define` like any plugin, as TUI built-ins do; "built-in" is only the host's flag for what `src/renderer.ts` and `src/main.ts` load. A third-party `./gui-experimental` bundle default-exports one `Plugin.define({ setup?, main?, ...declarations })`. No definition declares an id: the host gives a built-in its key in `compose` and a bundle the server plugin's id, as `ctx.id`. Main alone lists the plugins on the app's own server and sends windows their bundles; both hosts evaluate bundles only through `evaluatePluginBundle` in `@opencode/plugin/gui/host`, which owns the shape checks.
|
||||
- Every declaration field is declared once, in `Plugin.Declarations` (`packages/plugin/src/gui/declarations.ts`). `Plugin.Definition` adds the setups; the host's `Entry` (`@opencode/plugin/gui/host`) adds the lazy `windowEntry` and `mainEntry`. Every OS check goes through `runsOn`. A plugin from the config whose `os` leaves out this system never runs, and Extensions › Plugins keeps its row with "Not available on this system."
|
||||
- One folder per built-in: `index.ts` (`Plugin.define({ os?, stores?, icons?, i18n })`), `contract.ts`, `renderer.tsx`, an optional `main.ts`, `i18n/<locale>.ts`, and `icons/<name>.svg` for its own icons.
|
||||
- `src/renderer.ts` and `src/main.ts` are the only files that list the built-ins, each through `compose` from `@opencode/plugin/gui/host`, which attaches the lazy `windowEntry` and `mainEntry`. Main never imports window code.
|
||||
- `src/schemes.ts` collects built-in URL scheme declarations for registration before Electron is ready. Keep it free of runtime Electron and plugin setup imports; the owning plugin installs its handler only in its own partition.
|
||||
- Every plugin here ships. Do not add a plugin, fixture or wrapper only to document or demonstrate the SDK; the guide shows shipping code.
|
||||
- Another plugin may import only your `contract.ts` (tokens and schemas, no runtime code). Contracts are not declared: provide your own with `ctx.provide` (contracts from the window, Ipcs from main, each with an id under your plugin's id), call your own main entry with `ctx.main(Ipc)`, and follow another plugin's token with `ctx.use(token)`. Every built-in keeps working while any other is not active. To avoid loading an Ipc's schemas at startup, import its token only in the chunk that calls it.
|
||||
- A contract that returns components binds each with `bindPlugin` in the provider's setup, so `usePlugin` inside reads the provider's context, not the consumer's. Annotate the bound component's props (`bindPlugin((props: FileTreeProps) => ...)`): TypeScript cannot infer them inside `ctx.provide`. Do not wrap data methods such as `Changes.diffs`.
|
||||
|
|
|
|||
|
|
@ -373,6 +373,17 @@ to the displayed repository or worktree instead of adding a second menu item.
|
|||
| `ctx.embeds` (main) | `Embeds` | `create(view, window)` places a web page |
|
||||
| `ctx.cli` (main) | `Cli` | The opencode CLI the app runs |
|
||||
|
||||
### Contracts
|
||||
|
||||
The contracts `file`, `review` and `browser` publish with the SDK as `@opencode/plugin/gui/<name>`. Read one with `ctx.use`.
|
||||
|
||||
The desktop `Browser` contract (`@opencode/plugin/gui/browser`) can return a handle to a new tab in the session on screen:
|
||||
`const id = await browser.experimental.open(session, url)`, then `await browser.experimental.close(id)` from the same
|
||||
plugin instance. Experimental: may change without compatibility guarantees. The branded handle survives a session rebind.
|
||||
It ends with the plugin instance or the window, when the person clicks or types in the tab or runs a command on it, and
|
||||
when the agent uses the tab. `close` returns true only for a tab closed now; a page that asks "Leave site?" stays open.
|
||||
`open(session, url)` stays fire-and-forget.
|
||||
|
||||
### Built-in only
|
||||
|
||||
`@opencode/plugin/gui/builtin` holds what only the built-ins use. It is never published and is not in the modules a plugin bundle may require; a public SDK module never imports it.
|
||||
|
|
@ -382,8 +393,10 @@ to the displayed repository or worktree instead of adding a second menu item.
|
|||
| `onIdle(fn)` | Runs work while the main thread is idle, e.g. a lazy chunk's preload |
|
||||
| `BuiltinPanel`, `BuiltinPanelTab` | `legacy` stored keys of a panel; `first` and stable `dom` ids of a tab |
|
||||
| `BuiltinCommand` | `follows`: share another command's shortcut inside `scope` |
|
||||
| `BuiltinAppLink` | Review a person's activation of an application link in the desktop conversation |
|
||||
| `BuiltinPromptGate` | Work the host waits for, for at most one second, before it sends a prompt or a command |
|
||||
| `BuiltinStore`, `BuiltinStoreFrom` | Window stores imported from parts of the app's own keys |
|
||||
| `builtinContext(ctx)` | `ctx.desktop.forceFocus`, `ctx.locale.setDirection` |
|
||||
| `builtinContext(ctx)` | `ctx.desktop.forceFocus`, `ctx.locale.setDirection`, `ctx.provideFor` for per-consumer contracts |
|
||||
| `builtinMainContext(ctx)`, `MainStoreFrom`, `Lifecycle` | Main stores imported from settings files or other namespaces, and `lifecycle.restart(handoff)` |
|
||||
| `builtinCatalog(catalog)`, `BuiltinCatalog` | Locales other than English as loaders, loaded when the user picks the locale |
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
"exports": {
|
||||
"./renderer": "./src/renderer.ts",
|
||||
"./main": "./src/main.ts",
|
||||
"./schemes": "./src/schemes.ts",
|
||||
"./terminal": "./src/terminal/index.ts",
|
||||
"./debug/options": "./src/debug/options.ts"
|
||||
},
|
||||
|
|
@ -38,10 +39,12 @@
|
|||
"@tanstack/solid-query": "5.91.4",
|
||||
"@tanstack/solid-virtual": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"ffi-rs": "1.3.7",
|
||||
"fuzzysort": "catalog:",
|
||||
"ghostty-web": "github:anomalyco/ghostty-web#e91e38a9ceb13c566ddfa15185a9393849f712a9",
|
||||
"knobs": "npm:@kitlangton/knobs@0.4.0-next.22",
|
||||
"solid-js": "catalog:"
|
||||
"solid-js": "catalog:",
|
||||
"tldts": "7.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@happy-dom/global-registrator": "20.0.11",
|
||||
|
|
|
|||
79
packages/gui-plugins/src/browser/activation-delay.test.ts
Normal file
79
packages/gui-plugins/src/browser/activation-delay.test.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { ACTIVATION_DELAY_MS, actionGuard, activationAllowed, guardActivation } from "./activation-delay"
|
||||
|
||||
test("a prompt that shows again, as for a repeated request, starts its delay over", () => {
|
||||
const root = document.createElement("section")
|
||||
const allow = document.createElement("button")
|
||||
allow.dataset.activationGuard = ""
|
||||
root.append(allow)
|
||||
document.body.append(root)
|
||||
const answered: number[] = []
|
||||
allow.addEventListener("click", (event) => answered.push(event.timeStamp))
|
||||
const guard = guardActivation(root)
|
||||
|
||||
// Times are event timestamps from the moment the prompt shows, as the browser stamps them.
|
||||
const press = (at: number) => {
|
||||
for (const type of ["pointerdown", "click"]) {
|
||||
const event = new MouseEvent(type, { bubbles: true, cancelable: true })
|
||||
Object.defineProperty(event, "timeStamp", { value: at })
|
||||
Object.defineProperty(event, "isTrusted", { value: true })
|
||||
allow.dispatchEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
guard.changed()
|
||||
const shown = performance.now()
|
||||
press(shown + ACTIVATION_DELAY_MS + 100)
|
||||
expect(answered).toHaveLength(1)
|
||||
|
||||
// The page asks again: the same prompt shows anew, and a click 263 ms later does nothing.
|
||||
guard.changed()
|
||||
const again = performance.now()
|
||||
press(again + 263)
|
||||
expect(answered).toHaveLength(1)
|
||||
press(again + ACTIVATION_DELAY_MS + 1)
|
||||
expect(answered).toHaveLength(2)
|
||||
|
||||
guard.dispose()
|
||||
root.remove()
|
||||
})
|
||||
|
||||
test("a press that began before the prompt appeared, or elsewhere, never activates it", () => {
|
||||
expect(activationAllowed({ shownAt: 1_000, at: 5_000 })).toBe(false)
|
||||
expect(activationAllowed({ shownAt: 1_000, pressedAt: 950, at: 5_000 })).toBe(false)
|
||||
})
|
||||
|
||||
test("a press on the prompt activates it only once the prompt has been there long enough to read", () => {
|
||||
// A page's double-click target: the second click lands on the new bar 100 ms after it appears.
|
||||
expect(activationAllowed({ shownAt: 1_000, pressedAt: 1_100, at: 1_100 })).toBe(false)
|
||||
expect(
|
||||
activationAllowed({
|
||||
shownAt: 1_000,
|
||||
pressedAt: 1_000 + ACTIVATION_DELAY_MS - 50,
|
||||
at: 1_000 + ACTIVATION_DELAY_MS - 1,
|
||||
}),
|
||||
).toBe(false)
|
||||
// A press that began inside the delay does not count even when it ends after it; one that began after it does.
|
||||
expect(activationAllowed({ shownAt: 1_000, pressedAt: 1_400, at: 1_000 + ACTIVATION_DELAY_MS })).toBe(false)
|
||||
expect(activationAllowed({ shownAt: 1_000, pressedAt: 1_000 + ACTIVATION_DELAY_MS, at: 1_600 })).toBe(true)
|
||||
expect(ACTIVATION_DELAY_MS).toBe(500)
|
||||
})
|
||||
|
||||
test("a new bar requires a fresh press on the answered control after its delay", () => {
|
||||
const guard = actionGuard(20)
|
||||
const target = new EventTarget()
|
||||
const event = (timeStamp: number) => ({ isTrusted: true, currentTarget: target, timeStamp })
|
||||
guard.press(event(519))
|
||||
expect(guard.accept(event(530))).toBe(false)
|
||||
guard.press(event(600), true)
|
||||
expect(guard.accept(event(610))).toBe(false)
|
||||
guard.press(event(620))
|
||||
expect(actionGuard(621).accept(event(1300))).toBe(false)
|
||||
expect(guard.accept({ ...event(630), currentTarget: new EventTarget() })).toBe(false)
|
||||
guard.press(event(640))
|
||||
expect(guard.accept(event(650))).toBe(true)
|
||||
expect(guard.accept(event(660))).toBe(false)
|
||||
// A synthetic click never answers, even after a real press.
|
||||
guard.press(event(700))
|
||||
expect(guard.accept({ ...event(710), isTrusted: false })).toBe(false)
|
||||
})
|
||||
134
packages/gui-plugins/src/browser/activation-delay.ts
Normal file
134
packages/gui-plugins/src/browser/activation-delay.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// Input protection for what a page can make appear under the user's pointer or keys: refusal and pop-up notices,
|
||||
// permission bars and page dialogs. A page that shows one under a click or key press the user is already making must
|
||||
// not get that press on its controls, as browsers protect their own prompts.
|
||||
|
||||
/** How long a guarded control ignores presses after it appears or changes; Chromium uses about 500 ms. */
|
||||
export const ACTIVATION_DELAY_MS = 500
|
||||
|
||||
/**
|
||||
* Whether a press may activate a guarded control: it began (`pressedAt`) on that control at least `ACTIVATION_DELAY_MS`
|
||||
* after the control last appeared or changed (`shownAt`), and the activation (`at`) ends that press. A press that began
|
||||
* earlier, or elsewhere (no `pressedAt`), never activates it. All times are event timestamps on one clock.
|
||||
*/
|
||||
export function activationAllowed(input: {
|
||||
readonly shownAt: number
|
||||
readonly pressedAt?: number
|
||||
readonly at: number
|
||||
}) {
|
||||
return (
|
||||
input.pressedAt !== undefined &&
|
||||
input.pressedAt >= input.shownAt + ACTIVATION_DELAY_MS &&
|
||||
input.at >= input.pressedAt
|
||||
)
|
||||
}
|
||||
|
||||
type Press = Pick<Event, "isTrusted" | "timeStamp" | "currentTarget">
|
||||
|
||||
/**
|
||||
* One guard for the controls of one presentation, such as a notice's token: make a new one when it changes, not on
|
||||
* each render. A click activates only when a trusted, unrepeated press began on the same control (`activationAllowed`).
|
||||
*/
|
||||
export function actionGuard(shownAt: number) {
|
||||
let pressed: { target: EventTarget | null; at: number } | undefined
|
||||
|
||||
return {
|
||||
press(event: Press, repeat = false) {
|
||||
pressed = event.isTrusted && !repeat ? { target: event.currentTarget, at: event.timeStamp } : undefined
|
||||
},
|
||||
cancel() {
|
||||
pressed = undefined
|
||||
},
|
||||
accept(event: Press) {
|
||||
const press = pressed
|
||||
pressed = undefined
|
||||
|
||||
return (
|
||||
!!press &&
|
||||
event.isTrusted &&
|
||||
press.target === event.currentTarget &&
|
||||
activationAllowed({ shownAt, pressedAt: press.at, at: event.timeStamp })
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guards the controls inside `root` marked `data-activation-guard`, and the submission of its forms, with the same
|
||||
* rule: a click on one, or a submit, that `activationAllowed` refuses for the press that led to it is stopped before any
|
||||
* handler sees it. Call `changed` when the prompt shows something new in the same place.
|
||||
*
|
||||
* While `held` says so, as while an agent's show request has just put the prompt's tab in front of the person, nothing
|
||||
* in `root` answers: a click on any of its buttons, a submit and Escape are stopped, and a press made meanwhile counts
|
||||
* for nothing afterwards. Focus, the tab order and typing in its fields are left as they are.
|
||||
*/
|
||||
export function guardActivation(root: HTMLElement, held?: () => boolean) {
|
||||
let shownAt = performance.now()
|
||||
let pressed: { target: Element; at: number } | undefined
|
||||
|
||||
const stop = (event: Event) => {
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
}
|
||||
|
||||
// A key held down since before the prompt repeats on it; only a fresh, trusted press on the prompt counts.
|
||||
const press = (event: PointerEvent | KeyboardEvent) => {
|
||||
if (held?.()) {
|
||||
pressed = undefined
|
||||
|
||||
if (event instanceof KeyboardEvent && event.key === "Escape") stop(event)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const repeat = event instanceof KeyboardEvent && event.repeat
|
||||
|
||||
pressed =
|
||||
event.isTrusted && !repeat && event.target instanceof Element
|
||||
? { target: event.target, at: event.timeStamp }
|
||||
: undefined
|
||||
}
|
||||
|
||||
const activated = (event: Event) => {
|
||||
if (held?.()) {
|
||||
if (event.type === "submit" || (event.target instanceof Element && event.target.closest("button"))) stop(event)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const control =
|
||||
event.type === "submit"
|
||||
? event.target instanceof Element
|
||||
? event.target
|
||||
: null
|
||||
: event.target instanceof Element
|
||||
? event.target.closest("[data-activation-guard]")
|
||||
: null
|
||||
|
||||
if (!control) return
|
||||
|
||||
// A click needs its press on the same control; a submit, a press on the prompt, such as Enter in its field.
|
||||
const same = !!pressed && (event.type === "submit" || pressed.target.closest("[data-activation-guard]") === control)
|
||||
const trusted = event.type === "submit" || event.isTrusted
|
||||
|
||||
if (same && trusted && activationAllowed({ shownAt, pressedAt: pressed?.at, at: event.timeStamp })) return
|
||||
stop(event)
|
||||
}
|
||||
|
||||
root.addEventListener("pointerdown", press, true)
|
||||
root.addEventListener("keydown", press, true)
|
||||
root.addEventListener("click", activated, true)
|
||||
root.addEventListener("submit", activated, true)
|
||||
|
||||
return {
|
||||
changed() {
|
||||
shownAt = performance.now()
|
||||
pressed = undefined
|
||||
},
|
||||
dispose() {
|
||||
root.removeEventListener("pointerdown", press, true)
|
||||
root.removeEventListener("keydown", press, true)
|
||||
root.removeEventListener("click", activated, true)
|
||||
root.removeEventListener("submit", activated, true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,20 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { addressParts, resolveAddress } from "./address"
|
||||
import { addressParts, externalAction, externalPage, pageHandoff, resolveAddress } from "./address"
|
||||
import { remember, suggest } from "./history"
|
||||
import { normalizeURL, refusal } from "./policy"
|
||||
|
||||
test("typed file paths never become a host or a search query, regardless of the desktop OS", () => {
|
||||
const policy = { fileRoots: ["/work/repo"], home: "/work" }
|
||||
|
||||
for (const input of ["C:\\Users\\fixture\\x", "C:/Users/fixture/x", "\\\\server\\share\\x", "/other/x", "~/other/x", "../other/x", "file:/other/x"])
|
||||
expect(refusal(resolveAddress(input), policy)).toBe("browser.address.workspace")
|
||||
|
||||
for (const input of ["./index.html", "~/repo/index.html", "/work/repo/index.html", "file:/work/repo/index.html"])
|
||||
expect(normalizeURL(resolveAddress(input), policy)).toBe("file:///work/repo/index.html")
|
||||
|
||||
for (const [input, destination] of [["localhost:3000", "http://localhost:3000"], ["example.com/path", "https://example.com/path"], ["c.com", "https://c.com"], ["//example.com", "https://example.com"], ["find cats/dogs", "https://www.google.com/search?q=find%20cats%2Fdogs"]])
|
||||
expect(normalizeURL(resolveAddress(input), policy)).toBe(destination)
|
||||
})
|
||||
|
||||
test("the address field navigates to what reads as an address and searches for anything else", () => {
|
||||
const search = (query: string) => `https://www.google.com/search?q=${encodeURIComponent(query)}`
|
||||
|
|
@ -104,3 +118,45 @@ test("history keeps one newest-first visit per URL and suggests addresses that c
|
|||
),
|
||||
).toHaveLength(30)
|
||||
})
|
||||
|
||||
test("a local preview may be revealed by tab ID but never launched by URL", () => {
|
||||
for (const suffix of ["html", "exe", "bat", "cmd", "lnk", "ps1", "app"]) {
|
||||
expect(externalAction(`file:///repo/test.${suffix}`, true)).toBe("reveal")
|
||||
expect(externalAction(`file:///repo/test.${suffix}`, false)).toBeUndefined()
|
||||
}
|
||||
|
||||
expect(externalAction("https://example.org", false)).toBe("browser")
|
||||
expect(externalAction("oc-preview://other/repo/x", true)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("only a main-reported HTTP(S) failure can be handed off without a matching committed document", () => {
|
||||
const web = "https://localhost:4000/"
|
||||
const file = "file:///work/report.html"
|
||||
const preview = "oc-preview://grant/work/report.html"
|
||||
expect(pageHandoff("chrome-error://chromewebdata/", "about:blank", web, true, true)).toEqual({ kind: "web", url: web })
|
||||
expect(pageHandoff(web, web, "https://other.invalid/", false, true)).toBeUndefined()
|
||||
expect(pageHandoff(preview, file, file, true, true)).toBeUndefined()
|
||||
expect(pageHandoff(preview, file, file, false, true)).toEqual({ kind: "preview", url: file })
|
||||
expect(pageHandoff(file, file, file, false, true)).toBeUndefined()
|
||||
})
|
||||
|
||||
test.each([
|
||||
["https://example.org/page", false, true],
|
||||
["http://localhost:4000", true, true],
|
||||
["http://localhost:4000", false, false],
|
||||
["http://localhost.:4000", false, false],
|
||||
["http://foo.localhost.:4000", false, false],
|
||||
["http://0.0.0.0:4000", false, false],
|
||||
["http://[::]:4000", false, false],
|
||||
["http://[::ffff:127.0.0.1]:4000", false, false],
|
||||
["http://[::ffff:126.0.0.1]:4000", false, true],
|
||||
["file:///work/report.HTM#view", true, true],
|
||||
["file:///work/report.html.exe", true, false],
|
||||
["file:///work/report.html", false, false],
|
||||
["workspace://session/report.html", true, false],
|
||||
["artifact://item/report.html", true, false],
|
||||
["oc-preview://unknown/report.html", true, false],
|
||||
["mailto:hello@example.org", true, false],
|
||||
] as const)("the current page %s on this machine %s offers a hand-off: %s", (url, local, open) => {
|
||||
expect(externalPage(url, local)).toBe(open)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { destinationOrigin } from "./policy"
|
||||
import { destinationOrigin, localAddress } from "./policy"
|
||||
|
||||
/** Where text that is not an address goes. Shared with the system browser's default so results look familiar. */
|
||||
const SEARCH = "https://www.google.com/search?q="
|
||||
|
|
@ -25,6 +25,8 @@ export function searches(input: string) {
|
|||
|
||||
if (!value || /^about:\S*$/i.test(value)) return false
|
||||
|
||||
if (localAddress(value) || value.startsWith("//")) return false
|
||||
|
||||
if (/^[a-z][a-z\d+.-]*:\/\//i.test(value)) return !URL.canParse(value)
|
||||
|
||||
if (/\s/.test(value)) return true
|
||||
|
|
@ -53,6 +55,7 @@ export function addressParts(url: string) {
|
|||
* - `local`: HTTP on a loopback host, which resolves on the machine running the server.
|
||||
* - `insecure`: HTTP elsewhere.
|
||||
* - `file`: a workspace file.
|
||||
* - `workspace`: a file read by the session's server, not from the desktop's disk.
|
||||
*/
|
||||
export function connection(url: string) {
|
||||
if (!URL.canParse(url)) return
|
||||
|
|
@ -62,6 +65,8 @@ export function connection(url: string) {
|
|||
|
||||
if (parsed.protocol === "file:") return "file"
|
||||
|
||||
if (parsed.protocol === "workspace:") return "workspace"
|
||||
|
||||
if (parsed.protocol !== "http:") return
|
||||
|
||||
return loopback(parsed.hostname) ? "local" : "insecure"
|
||||
|
|
@ -69,5 +74,33 @@ export function connection(url: string) {
|
|||
|
||||
/** Whether a host names this machine; for a remote server that is the server's machine, not the user's. */
|
||||
export function loopback(hostname: string) {
|
||||
return /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\]|::1)$/i.test(hostname) || hostname.endsWith(".localhost")
|
||||
const host = hostname.toLowerCase().replace(/\.$/, "")
|
||||
|
||||
// URL.hostname canonicalizes IPv4-mapped IPv6 into hex groups, including mapped 0.0.0.0.
|
||||
return /^(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1?\]|::1|\[::ffff:(?:7f[\da-f]{2}:[\da-f]{1,4}|0:0)\])$/.test(host) || host.endsWith(".localhost")
|
||||
}
|
||||
|
||||
/** A file never goes to the default application. Main resolves the tab's workspace again before revealing it. */
|
||||
export function externalAction(url: string, local: boolean) {
|
||||
if (!URL.canParse(url)) return
|
||||
const parsed = new URL(url)
|
||||
|
||||
if (parsed.protocol === "file:") return local && !parsed.hostname ? "reveal" : undefined
|
||||
|
||||
if (destinationOrigin(url) && (local || !loopback(parsed.hostname))) return "browser"
|
||||
}
|
||||
|
||||
/** Eligibility of the displayed page; only main can turn a preview grant into a launchable file. */
|
||||
export function externalPage(url: string, local: boolean) {
|
||||
const action = externalAction(url, local)
|
||||
|
||||
return action === "browser" || (action === "reveal" && /\.html?$/i.test(new URL(url).pathname))
|
||||
}
|
||||
|
||||
/** `shown` is main's committed address or the URL Chromium reported failing, never a renderer-supplied target. */
|
||||
export function pageHandoff(actual: string, display: string, shown: string, failed: boolean, local: boolean) {
|
||||
if (externalAction(shown, local) === "browser" && (failed || actual === shown)) return { kind: "web" as const, url: shown }
|
||||
|
||||
if (!failed && actual.startsWith("oc-preview://") && display === shown && shown.startsWith("file:") && externalPage(shown, local))
|
||||
return { kind: "preview" as const, url: shown }
|
||||
}
|
||||
|
|
|
|||
116
packages/gui-plugins/src/browser/agent-rendering.test.ts
Normal file
116
packages/gui-plugins/src/browser/agent-rendering.test.ts
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
import { afterEach, expect, jest, test } from "bun:test"
|
||||
import { agentRendering, needsWakeFrame } from "./agent-rendering"
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
test("only the last command starts the idle clock; wake before the next command and cancel at disposal", () => {
|
||||
jest.useFakeTimers()
|
||||
const lifetime = new AbortController()
|
||||
const throttles: boolean[] = []
|
||||
const render = agentRendering(lifetime.signal, value => throttles.push(value))
|
||||
|
||||
const wait = render.hold()
|
||||
render.hold()[Symbol.dispose]()
|
||||
jest.advanceTimersByTime(30_000)
|
||||
expect(throttles).toEqual([false])
|
||||
wait[Symbol.dispose]()
|
||||
jest.advanceTimersByTime(29_999)
|
||||
const followup = render.hold()
|
||||
jest.advanceTimersByTime(30_000)
|
||||
expect(throttles).toEqual([false])
|
||||
followup[Symbol.dispose]()
|
||||
jest.advanceTimersByTime(29_999)
|
||||
expect(throttles).toEqual([false])
|
||||
jest.advanceTimersByTime(1)
|
||||
render.committed()
|
||||
expect(throttles).toEqual([false, true])
|
||||
render.hold()[Symbol.dispose]()
|
||||
expect(throttles).toEqual([false, true, false])
|
||||
lifetime.abort()
|
||||
jest.advanceTimersByTime(30_000)
|
||||
expect(throttles).toEqual([false, true, false])
|
||||
})
|
||||
|
||||
test("overlapping commands await the same first frame", async () => {
|
||||
const render = agentRendering(new AbortController().signal, () => {})
|
||||
const frame = Promise.withResolvers<void>()
|
||||
const first = render.hold(() => frame.promise)
|
||||
const second = render.hold(() => { throw new Error("duplicate wake") })
|
||||
expect(second.painted).toBe(first.painted)
|
||||
frame.resolve()
|
||||
await first.painted
|
||||
first[Symbol.dispose]()
|
||||
second[Symbol.dispose]()
|
||||
})
|
||||
|
||||
test("a command that needs no frame wakes the page without one; the next one that needs a frame still waits", async () => {
|
||||
jest.useFakeTimers()
|
||||
const throttles: boolean[] = []
|
||||
const frames: ReturnType<typeof Promise.withResolvers<void>>[] = []
|
||||
const render = agentRendering(new AbortController().signal, value => throttles.push(value))
|
||||
|
||||
const wake = () => {
|
||||
const frame = Promise.withResolvers<void>()
|
||||
frames.push(frame)
|
||||
|
||||
return frame.promise
|
||||
}
|
||||
|
||||
for (const method of ["frames", "dialog"] as const) {
|
||||
const passive = render.hold(needsWakeFrame(method, true, false) ? wake : undefined)
|
||||
expect(passive.painted).toBeUndefined()
|
||||
passive[Symbol.dispose]()
|
||||
}
|
||||
|
||||
expect(throttles).toEqual([false])
|
||||
expect(frames).toHaveLength(0)
|
||||
// The page is awake but has painted nothing since: an immediate snapshot waits for its first frame.
|
||||
const snapshot = render.hold(needsWakeFrame("snapshot", true, false) ? wake : undefined)
|
||||
expect(snapshot.painted).toBeDefined()
|
||||
expect(frames).toHaveLength(1)
|
||||
frames[0]?.resolve()
|
||||
await snapshot.painted
|
||||
const click = render.hold(needsWakeFrame("click", true, false) ? wake : undefined)
|
||||
expect(click.painted).toBeUndefined()
|
||||
expect(frames).toHaveLength(1)
|
||||
snapshot[Symbol.dispose]()
|
||||
click[Symbol.dispose]()
|
||||
// Throttled again after the idle time, the page owes the next painting command a fresh frame.
|
||||
jest.advanceTimersByTime(30_000)
|
||||
expect(throttles).toEqual([false, true])
|
||||
expect(render.hold(wake).painted).toBeDefined()
|
||||
expect(frames).toHaveLength(2)
|
||||
})
|
||||
|
||||
test("idle past the deadline with a dialog open, the dialog command un-throttles without waiting for a frame", () => {
|
||||
jest.useFakeTimers()
|
||||
const throttles: boolean[] = []
|
||||
const render = agentRendering(new AbortController().signal, value => throttles.push(value))
|
||||
|
||||
render.hold()[Symbol.dispose]()
|
||||
jest.advanceTimersByTime(30_000)
|
||||
expect(throttles).toEqual([false, true])
|
||||
|
||||
// An open alert pauses the page's animation frames, so no command waits for one, including the one that answers it.
|
||||
for (const method of ["dialog", "snapshot", "click", "navigate"] as const) expect(needsWakeFrame(method, true, true)).toBe(false)
|
||||
|
||||
const answer = render.hold(needsWakeFrame("dialog", true, true) ? () => new Promise(() => {}) : undefined)
|
||||
expect(answer.painted).toBeUndefined()
|
||||
expect(throttles).toEqual([false, true, false])
|
||||
})
|
||||
|
||||
test("a renderer that never paints neither blocks navigation nor fails the command that waited for it", async () => {
|
||||
const render = agentRendering(new AbortController().signal, () => {})
|
||||
const frame = Promise.withResolvers<void>()
|
||||
const snapshot = render.hold(needsWakeFrame("snapshot", true, false) ? () => frame.promise : undefined)
|
||||
expect(snapshot.painted).toBeDefined()
|
||||
|
||||
for (const method of ["navigate", "reload", "stop", "back", "dialog", "tabs.close"] as const) expect(needsWakeFrame(method, true, false)).toBe(false)
|
||||
expect(needsWakeFrame("snapshot", false, false)).toBe(false)
|
||||
expect(render.hold(needsWakeFrame("navigate", true, false) ? () => frame.promise : undefined).painted).toBeUndefined()
|
||||
// The capture deadline rejects the wake; the snapshot then proceeds as it would without one.
|
||||
frame.reject(new Error("no frame"))
|
||||
await expect(snapshot.painted).resolves.toBeUndefined()
|
||||
})
|
||||
61
packages/gui-plugins/src/browser/agent-rendering.ts
Normal file
61
packages/gui-plugins/src/browser/agent-rendering.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import type { Browser } from "@opencode/plugin-browser/rpc"
|
||||
|
||||
/** A paused page cannot paint the frame that its dialog or a recovery navigation would unblock. */
|
||||
export function needsWakeFrame(method: Browser.Method, loaded: boolean, dialog: boolean) {
|
||||
const painting: Browser.Method[] = ["snapshot", "find", "wait", "evaluate", "click", "check", "fill", "fill_form", "select", "press", "hover", "drag", "scroll", "screenshot"]
|
||||
|
||||
return loaded && !dialog && painting.includes(method)
|
||||
}
|
||||
|
||||
// Long enough to cover thinking between a snapshot and its follow-up; a forgotten tab doesn't animate indefinitely.
|
||||
const idleMs = 30_000
|
||||
|
||||
export function agentRendering(signal: AbortSignal, throttle: (enabled: boolean) => void) {
|
||||
let holds = 0
|
||||
let awake = false
|
||||
// Whether a frame was waited for since the page woke. A command that needs no frame (`frames`, `console`, `dialog`)
|
||||
// wakes the page without one, and the next command that needs one must still wait for it.
|
||||
let painted = false
|
||||
let paint: Promise<void> | undefined
|
||||
let idle: ReturnType<typeof setTimeout> | undefined
|
||||
signal.addEventListener("abort", () => clearTimeout(idle), { once: true })
|
||||
|
||||
return {
|
||||
hold(onWake?: () => Promise<void>) {
|
||||
signal.throwIfAborted()
|
||||
clearTimeout(idle)
|
||||
|
||||
if (!awake) throttle(false)
|
||||
awake = true
|
||||
holds++
|
||||
|
||||
if (onWake && !painted && !paint) {
|
||||
const frame = onWake().catch(() => undefined)
|
||||
paint = frame
|
||||
// A renderer that never paints is not asked again: the command proceeds as it would without a frame.
|
||||
void frame.then(() => {
|
||||
painted = true
|
||||
|
||||
if (paint === frame) paint = undefined
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
painted: onWake ? paint : undefined,
|
||||
[Symbol.dispose]() {
|
||||
if (--holds || signal.aborted) return
|
||||
idle = setTimeout(() => {
|
||||
awake = false
|
||||
painted = false
|
||||
paint = undefined
|
||||
throttle(true)
|
||||
}, idleMs)
|
||||
},
|
||||
}
|
||||
},
|
||||
// A cross-site commit can replace the renderer while a command or its grace period is active.
|
||||
committed() {
|
||||
if (awake && !signal.aborted) throttle(false)
|
||||
},
|
||||
}
|
||||
}
|
||||
72
packages/gui-plugins/src/browser/artifact-link.test.ts
Normal file
72
packages/gui-plugins/src/browser/artifact-link.test.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import { artifactAddress, artifactLink, artifactResource, artifactWebURL } from "./artifact-link"
|
||||
import { createHandlePath } from "./disk"
|
||||
import { resolvePreviewRequest, type PreviewSource } from "./workspace-file"
|
||||
|
||||
const base = "https://example.test:444/mounted"
|
||||
|
||||
const view = "/api/experimental/artifacts/art_aBc123/view"
|
||||
|
||||
const display = "artifact://art_aBc123/"
|
||||
|
||||
test("only this server's artifact view is a pane link, including behind a base path", () => {
|
||||
for (const root of [view, `${base}${view}`]) {
|
||||
expect(artifactLink(root, base)).toBe(display)
|
||||
expect(artifactLink(`${root}/`, base)).toBe(display)
|
||||
expect(artifactLink(`${root}/assets/50%25.svg`, base)).toBe(`${display}assets/50%25.svg`)
|
||||
}
|
||||
|
||||
expect(artifactLink(`https://EXAMPLE.test:443${view}`, "https://example.test")).toBe(display)
|
||||
|
||||
for (const other of [
|
||||
"https://provider.test/report",
|
||||
`https://example.test${view}`,
|
||||
`${base}.other${view}`,
|
||||
`${view}er/`,
|
||||
view.replace("/view", "/update"),
|
||||
view.replace("art_aBc123", "art_"),
|
||||
`${view}?location=other`,
|
||||
`${view}/../x`,
|
||||
`${view}/%2e%2e/x`,
|
||||
`${view}/a%2fb`,
|
||||
`${view}/a%5cb`,
|
||||
`${view}//host`,
|
||||
`${view}/a\\b`,
|
||||
])
|
||||
expect(artifactLink(other, base)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("an artifact address round trips without the server URL; web uses its ordinary view URL", () => {
|
||||
const path = "assets/50%25.svg"
|
||||
expect(artifactAddress(display + path)).toEqual({ id: "art_aBc123", path })
|
||||
expect(artifactWebURL(display + path, base)).toBe(`${base}${view}/${path}`)
|
||||
expect(artifactWebURL(display, "https://name:pass@example.test")).toBeUndefined()
|
||||
expect(artifactResource(`oc-preview://grant/${path}?ignored=yes#fragment`, "grant", "art_aBc123")).toEqual({
|
||||
display: display + path,
|
||||
route: `${view}/${path}`,
|
||||
})
|
||||
})
|
||||
|
||||
test("no foreign origin, path or method can choose where the grant sends credentials", async () => {
|
||||
const grants = new Map<string, PreviewSource>([
|
||||
["first", { type: "artifact", id: "art_aBc123", read: () => Promise.reject(new Error("not a byte read")) }],
|
||||
])
|
||||
|
||||
const request = (path: string, method = "GET", origin: string | undefined = "oc-preview://first") =>
|
||||
resolvePreviewRequest(`oc-preview://first/${path}`, method, origin, grants, AbortSignal.timeout(1000), createHandlePath())
|
||||
|
||||
expect(await request("")).toMatchObject({ route: `${view}/` })
|
||||
expect(await request("assets/app.js?location[directory]=other", "HEAD")).toMatchObject({
|
||||
route: `${view}/assets/app.js`,
|
||||
})
|
||||
expect(await request("api/session")).toMatchObject({ route: `${view}/api/session` })
|
||||
|
||||
for (const path of ["../x", "%2e%2e/x", "c:/x", "/other", "x%2fy", "x%5cy", "x\\y"])
|
||||
expect(await request(path)).toBeUndefined()
|
||||
|
||||
for (const origin of ["https://web.test", "null", "oc-preview://second"])
|
||||
expect(await request("", "GET", origin)).toBeUndefined()
|
||||
expect(await request("index.html", "POST")).toBeUndefined()
|
||||
grants.clear()
|
||||
expect(await request("")).toBeUndefined()
|
||||
})
|
||||
69
packages/gui-plugins/src/browser/artifact-link.ts
Normal file
69
packages/gui-plugins/src/browser/artifact-link.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { remotePath } from "./remote-address"
|
||||
|
||||
const route = "/api/experimental/artifacts/"
|
||||
|
||||
export function artifactViewPath(item: { id: string; path: string }) {
|
||||
return `${route}${item.id}/view/${item.path}`
|
||||
}
|
||||
|
||||
/** Parse the path as written, before URL normalization could erase a traversal or repair an authority. */
|
||||
function parts(value: string) {
|
||||
const match = /^(art_[a-zA-Z0-9]+)\/(.*)$/u.exec(value)
|
||||
|
||||
if (!match || /[?#\s\x00-\x1f]/u.test(value)) return
|
||||
const path = match[2] ? remotePath(match[2], "", true) : ""
|
||||
|
||||
if (path === undefined) return
|
||||
|
||||
return { id: match[1], path: path.split("/").map(encodeURIComponent).join("/") }
|
||||
}
|
||||
|
||||
/** Only the view route on this exact server (never its metadata, or a look-alike origin). */
|
||||
export function artifactLink(href: string, server: string) {
|
||||
const authority = /^(https?:\/\/[^/?#\\\s@]+)(\/.*)$/iu.exec(href)
|
||||
// Compare origins as URLs, but compare paths as written: a URL parser would erase dot segments.
|
||||
const base = authority && URL.canParse(server) && URL.canParse(authority[1]) ? new URL(server) : undefined
|
||||
const prefix = `${base?.pathname.replace(/\/+$/, "") ?? ""}${route}`
|
||||
|
||||
const rest = href.startsWith(route)
|
||||
? href.slice(route.length)
|
||||
: base &&
|
||||
authority &&
|
||||
!base.username &&
|
||||
!base.password &&
|
||||
new URL(authority[1]).origin === base.origin &&
|
||||
authority[2].startsWith(prefix)
|
||||
? authority[2].slice(prefix.length)
|
||||
: undefined
|
||||
|
||||
const match = rest && /^(art_[a-zA-Z0-9]+)\/view(?:\/(.*))?$/u.exec(rest)
|
||||
const item = match && parts(`${match[1]}/${match[2] ?? ""}`)
|
||||
|
||||
return item ? `artifact://${item.id}/${item.path}` : undefined
|
||||
}
|
||||
|
||||
export function artifactAddress(address: string) {
|
||||
return address.startsWith("artifact://") ? parts(address.slice(11)) : undefined
|
||||
}
|
||||
|
||||
/** A grant translates only its own origin. No page-supplied query, fragment or path becomes an API selector. */
|
||||
export function artifactResource(url: string, host: string, id: string) {
|
||||
const prefix = `oc-preview://${host}/`
|
||||
|
||||
if (!url.startsWith(prefix)) return
|
||||
const item = parts(`${id}/${url.slice(prefix.length).split(/[?#]/, 1)[0]}`)
|
||||
|
||||
return item && { display: `artifact://${id}/${item.path}`, route: artifactViewPath(item) }
|
||||
}
|
||||
|
||||
/** The public link the web app opens in a separate browser tab, without supplying server credentials. */
|
||||
export function artifactWebURL(address: string, server: string) {
|
||||
const item = artifactAddress(address)
|
||||
|
||||
if (!item || !URL.canParse(server)) return
|
||||
const base = new URL(server)
|
||||
|
||||
if (!/^https?:$/.test(base.protocol) || base.username || base.password || base.search || base.hash) return
|
||||
|
||||
return `${base.href.replace(/\/+$/, "")}${artifactViewPath(item)}`
|
||||
}
|
||||
55
packages/gui-plugins/src/browser/artifact-links.ts
Normal file
55
packages/gui-plugins/src/browser/artifact-links.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import type { Cdp } from "./cdp"
|
||||
import { destinationOrigin } from "./policy"
|
||||
|
||||
/** UX only: the native navigation fence and the document's network allowlist do not depend on this script. */
|
||||
export function artifactLinks(cdp: Cdp, current: () => string | undefined, offer: (url: string) => void) {
|
||||
const world = "opencode-artifact-links"
|
||||
const binding = "openCodeArtifactLink"
|
||||
const installed = new Map<string, Promise<void>>()
|
||||
let ready: Promise<void> | undefined
|
||||
|
||||
cdp.on("Runtime.bindingCalled", (event, sessionID) => {
|
||||
if (
|
||||
!sessionID &&
|
||||
current() &&
|
||||
event.name === binding &&
|
||||
event.payload.length <= 16384 &&
|
||||
destinationOrigin(event.payload)
|
||||
)
|
||||
offer(event.payload)
|
||||
})
|
||||
|
||||
return (host: string) => {
|
||||
const prior = installed.get(host)
|
||||
|
||||
if (prior) return prior
|
||||
ready ??= cdp.send("Runtime.addBinding", { name: binding, executionContextName: world }).then(() => undefined)
|
||||
|
||||
const install = ready
|
||||
.then(() =>
|
||||
cdp.send("Page.addScriptToEvaluateOnNewDocument", {
|
||||
worldName: world,
|
||||
runImmediately: true,
|
||||
source: `
|
||||
if (location.protocol === 'oc-preview:' && location.host === ${JSON.stringify(host)}) {
|
||||
const external = value => { try { return /^https?:$/.test(new URL(value).protocol) } catch { return false } };
|
||||
addEventListener('click', event => {
|
||||
const url = event.composedPath().find(node => node instanceof HTMLAnchorElement)?.href;
|
||||
if (!url || !external(url)) return;
|
||||
event.preventDefault();
|
||||
if (event.isTrusted) ${binding}(url);
|
||||
}, true);
|
||||
navigation.addEventListener('navigate', event => {
|
||||
if (event.cancelable && external(event.destination.url)) event.preventDefault();
|
||||
});
|
||||
}
|
||||
`,
|
||||
}),
|
||||
)
|
||||
.then(() => undefined)
|
||||
|
||||
installed.set(host, install)
|
||||
|
||||
return install
|
||||
}
|
||||
}
|
||||
41
packages/gui-plugins/src/browser/artifact-preview.test.ts
Normal file
41
packages/gui-plugins/src/browser/artifact-preview.test.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { afterAll, beforeAll, expect, test } from "bun:test"
|
||||
import { GlobalRegistrator } from "@happy-dom/global-registrator"
|
||||
import { artifactPages } from "./artifact-preview"
|
||||
|
||||
beforeAll(() => GlobalRegistrator.unregister())
|
||||
|
||||
afterAll(() => GlobalRegistrator.register())
|
||||
|
||||
test("preflight asks this server for the entry before allocating a tab or granting bytes", async () => {
|
||||
const server = Bun.serve({
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
expect(request.method).toBe("HEAD")
|
||||
expect(url.searchParams.get("location[directory]")).toBe("/project")
|
||||
|
||||
return new Response(null, { status: url.pathname === "/api/experimental/artifacts/art_here/view/" ? 200 : 404 })
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
const artifacts = artifactPages(
|
||||
{
|
||||
failure: () => undefined,
|
||||
grant: () => {
|
||||
throw new Error("unexpected grant")
|
||||
},
|
||||
dispose() {},
|
||||
},
|
||||
{ id: "server", url: server.url.href, headers: {}, sameMachine: false },
|
||||
"/project",
|
||||
new AbortController().signal,
|
||||
)
|
||||
|
||||
expect(await artifacts.exists("artifact://art_here/")).toBe(true)
|
||||
expect(await artifacts.exists("artifact://art_elsewhere/")).toBe(false)
|
||||
} finally {
|
||||
await server.stop(true)
|
||||
}
|
||||
})
|
||||
61
packages/gui-plugins/src/browser/artifact-preview.ts
Normal file
61
packages/gui-plugins/src/browser/artifact-preview.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import type { ServerEndpoint } from "@opencode/plugin/gui/main"
|
||||
import { artifactAddress, artifactResource, artifactViewPath } from "./artifact-link"
|
||||
import type { createPreviews } from "./profile/previews"
|
||||
|
||||
/** One tab's grants, allocated only by a deliberate load/restore, never by an incoming protocol request. */
|
||||
export function artifactPages(
|
||||
previews: ReturnType<typeof createPreviews>,
|
||||
server: ServerEndpoint,
|
||||
directory: string,
|
||||
lifetime: AbortSignal,
|
||||
) {
|
||||
const grants = new Map<string, ReturnType<typeof previews.grant>>()
|
||||
|
||||
const read = (route: string, method: string, signal: AbortSignal) => {
|
||||
const url = new URL(`${server.url.replace(/\/+$/, "")}${route}`)
|
||||
url.searchParams.set("location[directory]", directory)
|
||||
|
||||
return fetch(url, {
|
||||
headers: server.headers,
|
||||
redirect: "error",
|
||||
method,
|
||||
signal: AbortSignal.any([signal, lifetime]),
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
load(address: string) {
|
||||
const item = artifactAddress(address)
|
||||
|
||||
if (!item) return
|
||||
const grant = grants.get(item.id) ?? previews.grant({ type: "artifact", id: item.id, read }, lifetime)
|
||||
grants.set(item.id, grant)
|
||||
|
||||
return `oc-preview://${grant.host}/${item.path}`
|
||||
},
|
||||
display(url: string) {
|
||||
if (!url.startsWith("oc-preview:")) return
|
||||
|
||||
for (const [id, grant] of grants) {
|
||||
const resource = artifactResource(url, grant.host, id)
|
||||
|
||||
if (resource) return resource.display
|
||||
}
|
||||
},
|
||||
async exists(url: string) {
|
||||
const item = artifactAddress(url)
|
||||
|
||||
// Before opening a tab this also checks a link received in chat, without issuing a grant.
|
||||
if (!item) return false
|
||||
|
||||
return read(artifactViewPath(item), "HEAD", AbortSignal.timeout(15_000)).then(
|
||||
(r) => r.status === 200,
|
||||
() => false,
|
||||
)
|
||||
},
|
||||
dispose() {
|
||||
grants.forEach((grant) => grant.release())
|
||||
grants.clear()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -112,6 +112,16 @@
|
|||
color: var(--v2-text-text-base);
|
||||
}
|
||||
|
||||
/* Drop path text first. If the authority itself is too long, keep its right edge, not the page-chosen prefix. */
|
||||
[data-slot="browser-address-url"][data-web] {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
[data-slot="browser-address-authority"] { display: flex; flex: none; max-width: 100%; }
|
||||
[data-slot="browser-address-muted"] { flex: none; }
|
||||
[data-slot="browser-address-host"] { direction: rtl; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
[data-slot="browser-address-rest"] { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
}
|
||||
|
||||
/* The page's zoom when it is not 100%, drawn like the zoom badge in the browser options. */
|
||||
[data-slot="browser-address-zoom"] {
|
||||
flex: none;
|
||||
|
|
@ -501,11 +511,34 @@
|
|||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* Centers the icon on the first line of the row's text. */
|
||||
/* The row that leads to "Site settings": a button drawn as a row. */
|
||||
button[data-slot="browser-site-row"] {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
letter-spacing: inherit;
|
||||
cursor: default;
|
||||
|
||||
&:hover {
|
||||
background: var(--v2-overlay-simple-overlay-hover);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 1px solid var(--v2-border-border-focus);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
}
|
||||
|
||||
/* The icon column: centers the icon on the first line of the row's text. A control wider than the column, such as
|
||||
the back button, is centered on it too, so its glyph stays in the column. */
|
||||
[data-slot="browser-site-icon"] {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 20px;
|
||||
color: var(--v2-icon-icon-muted);
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue