diff --git a/.github/release/entitlements/desktop.plist b/.github/release/entitlements/desktop.plist index cb9a9891fa54..449dd125d46f 100644 --- a/.github/release/entitlements/desktop.plist +++ b/.github/release/entitlements/desktop.plist @@ -6,5 +6,7 @@ com.apple.security.device.audio-input + com.apple.security.device.camera + diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index 3a8acaa600b8..4506cf49fefa 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -16,7 +16,4 @@ "tools": { "github-pr-search": false, }, - "experimental": { - "part_rows": true, - }, } diff --git a/.opencode/skills/focus-states/SKILL.md b/.opencode/skills/focus-states/SKILL.md new file mode 100644 index 000000000000..fb255243cf40 --- /dev/null +++ b/.opencode/skills/focus-states/SKILL.md @@ -0,0 +1,72 @@ +--- +name: focus-states +description: Focus indicators and focus movement in OpenCode Desktop and the web app. Use when adding or reviewing an interactive component, a :focus/:focus-visible/:focus-within rule, an outline on focus, a list/menu/palette row, a text field, a dialog, menu or popover, a selected state, removing or closing a focused item, or anything that moves focus programmatically. +--- + +# Focus States + +Use one default ring when someone navigates focus to a control, not when they click or tap it. The exceptions are below. Desktop uses Chromium; on the web, test the browser you’re changing or targeting rather than assuming identical focus behaviour. + +## The ring + +- Use `:focus-visible` for the ring. Don’t use `:focus` to decide whether to show it. The only exception is a custom field that combines `:focus` with its own ring state, as the composer and Home search do (see Text fields). `base.css` supplies `outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px` and a 4px radius for links. +- Offset: `2px` outward by default. `-2px` inset for full-width rows and for controls flush against an edge that clips or scrolls (segmented items, split buttons, titlebar buttons, clear buttons). No other offsets. +- Follow the control’s radius; give a square text action or link 4px where appropriate. Use a wrapper with `:has(> trigger:focus-visible)` when the wrapper owns the visible shape or the trigger’s ring would clip, as with tabs and Settings project cards. +- Outline only. Don't draw focus with `box-shadow`: Windows High Contrast removes shadows, so the ring disappears, and shadow rings looked different from every other ring. +- Rings appear and disappear instantly. Draw no outline at rest and leave `outline-color` out of `transition`; animating it from the default colour flashes black. Don't use `outline: 2px solid transparent` at rest: High Contrast turns it into a visible outline on every control. +- Keep a border that identifies an unfocused control. Where Chromium's forced colours remove the shadow that draws a control's edge, give it a system-colour border in `@media (forced-colors: active)`, separate from the ring, as switches and radios do. +- Inline rename inputs rely on the caret and editing state. The timeline's Jump to latest stays in the Tab order with the shared ring, since it's the only quick way back down from the keyboard; its container is `inert` while it's hidden. Loading alone doesn’t add a ring. If a busy button keeps keyboard focus, keep the ring and show the busy state separately with `aria-busy`, a disabled state, or loading text; the ring alone doesn’t say whether the button can be activated. +- These ring rules do not replace normal field borders or validation feedback. Those can respond to click focus and have their own inset treatment. + +## Text fields + +Editable fields can match `:focus-visible` after a click, so fields with a custom frame ring (the composer and Home search) decide when focus arrives. Use `packages/ui/src/context/field-focus.tsx`, not a global input tracker. + +- Ring by default. Suppress the ring for direct pointer focus and for the composer’s explicit initial autofocus when a session or draft opens, including when it was opened with the keyboard. +- Tab, shortcuts like Find, and assistive technology moving DOM focus show the ring. Moving a screen reader’s reading cursor alone does not move DOM focus. +- When a dialog returns focus to a custom field, `packages/ui/src/context/dialog.tsx` restores the field's own ring state; ordinary controls use the browser's `:focus-visible` state. The overlay rules below apply. +- A `pointerdown` inside a field that already shows the ring clears it immediately; no new focus event fires. Typing never changes the decision, and blur clears it. +- A click shows the field's normal focused border or background and the caret, with no ring. + +## Rows + +- Choose by how focus moves. + - Focus stays in a search input while arrow keys move a highlight (`aria-activedescendant`: palettes, search lists): the active option is background-only and should not also be a Tab stop. Independent actions can still be Tab stops. + - A full-width row that is its own Tab stop (Home sessions and projects, settings rows) gets a 2px inset ring. Standalone disclosure and tool triggers can use an outset ring if it fits. Hover stays background-only. + - With roving focus (tabs and file trees), Tab enters the widget and arrow keys move focus within it. Show a ring on the keyboard-focused item, even though the other items are not separate Tab stops. +- The active option’s background highlight can disappear or become too faint in forced colours. Use `Highlight` and `HighlightText` in `@media (forced-colors: active)`. Check that nested labels and icons remain readable. +- Selection is not focus. Keep it neutral and distinct from the blue ring. The Settings › General layout cards (`settings/general/interface-mode.css`) are the reference for picker cards: a 2px `--v2-border-border-strong` border, a check badge outside the corner (`--v2-icon-icon-muted` fill, cut out in the surface colour, with a system-colour border in forced colours), and the other options' content faded. Don't use the inverse (black) border. + +## Overlays and menus + +- When an overlay closes and returns focus to its opener: + - Pointer dismissals (backdrop click, a close button clicked with the pointer) restore the opener’s ring state from when the overlay opened. + - Escape or another keyboard close after a keyboard open shows the ring on the restored control. + - Escape after a pointer open restores the no-ring state. Changing that is a deliberate product decision and needs its own test. +- Dialogs get this from the dialog context and dropdown menus from the `Menu` wrapper. Select, `Menu.Context`, and raw `@kobalte/core/popover` uses get it from `createOverlayFocus` in `packages/ui/src/context/overlay-focus.tsx`: call `openChanged` from `onOpenChange` and `restore(event, trigger)` from `onCloseAutoFocus`. Without a trigger, `restore(event)` returns to whatever had focus when it opened, such as a context menu's row. Never call a bare `trigger.focus()` on close. +- Choose the widget by what's inside, not by how it looks. A menu (`Menu`, `role="menu"`) holds only commands: arrow keys, Home/End and typeahead move, Enter chooses, Esc closes, and Tab does nothing, as in native menus. A popover that holds controls (switches, links, buttons in flyouts, like the Extensions panel) must let Tab move through them; arrow keys may be added on top. + +## Clipping and covering + +- Use `overflow: clip; overflow-clip-margin: 5px` only if the container does not need to scroll, including programmatic scrolling. For scrollers, use an inset ring, padding, or scroll margins as appropriate. +- Rows that overlap by a pixel to merge borders (accordions) let the next row paint over the bottom of an inset ring. Raise the header holding focus (`z-index`), as `accordion.css` and `sticky-accordion-header.css` do; with sticky headers, raise the header, not the item, or the item lands under its neighbours' sticky headers. +- Keep the whole ring clear of sticky content. Try an inset ring or a targeted `scroll-margin` on the affected items first. Use `scroll-padding` on the scroller only when sticky chrome covers focus across the whole area, since it changes every scroll, not just focus. Account for the header, any fade, and the ring’s reach (4px for the default outset ring). Check Tab and Shift+Tab. + +## Colour and contrast + +- Use `--v2-border-border-focus`, never a raw colour or a per-component override. It is Blue 500 in light and Blue 400 in dark; custom themes can override it. +- Light mode has a known contrast gap: Blue 500 is about 2.7:1 on white, below the 3:1 target. It was kept as a documented decision because Blue 600 read too heavy. It is not a pass, and 2.7:1 is not a new threshold. +- Measure against the actual adjacent colours in both schemes: the surrounding surface for an outset ring and the control’s fill for an inset ring. If contrast is low, first try a placement that improves it without clipping. If placement can’t fix it, flag the shortfall and revisit the token. Never change the colour per component. + +## Order and movement + +- Follow logical reading and interaction order, including in RTL. Fix DOM order rather than using positive `tabindex`. Use native buttons for actions and links for navigation; use established widget primitives or keyboard patterns for tabs, trees, sliders, and resize handles. +- Move focus in response to a user action or to recover focus when its target disappears. Background updates, streamed output, toasts, and incoming prompts must not steal focus. +- If a focused item is closed or deleted, move focus to the next place the user can continue the same task: the next or previous item in the same list, or a stable fallback such as the list heading or the control that opened it. Use the visually nearest control only when it serves that task. Don’t leave focus on ``. +- Chromium drops focus to `` without an event when the focused element is removed, disabled, or stops being editable. `packages/ui/src/context/focus-rescue.tsx` (installed in `AppBaseProviders`) recovers it inside a `data-focus-scope`: the next item, or the previous after the last, widening to the enclosing scope when the inner one is empty, and back to what had focus before when nothing is left. Mark a new list, strip, chip row or panel with `data-focus-scope` rather than adding per-feature focus code. Rescue never moves focus into a `role="tablist"`, because Kobalte tabs select themselves on focus, so don't mark a tab list as a scope. Items in an overlay leave the return to the overlay; rescue steps in only when the overlay's opener is gone too. Move focus explicitly when the task has a better target than the neighbour, such as the composer after the last chip. + +## Verify + +- A story is optional, for visual checks such as clipping, colour, and forced colours. Use one if the repo has a suitable focus story, or a local one you don't commit; don't add a case for every fix. Test focus order, removal and restoration in the app with real input, not in a story. +- Use real keyboard and pointer input for the behaviour you changed. Check Tab and Shift+Tab for order and clipping, arrow keys for composites, and shortcuts for programmatic focus. For overlay return, check keyboard open with Escape, keyboard open with a pointer dismissal, pointer open with a backdrop click, and pointer open with Escape. Forced focus shows appearance, not whether navigation or restoration works. +- Check light, dark, and forced colours when the indicator or its background changes. Report Chromium forced-colours emulation (DevTools → Rendering → `forced-colors: active`) separately from native Windows High Contrast or assistive-technology testing. diff --git a/.oxlintrc.json b/.oxlintrc.json index 0ad3ae0a5cc8..08499c44323b 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -179,33 +179,6 @@ } ] } - }, - { - "files": ["packages/codemode/src/interpreter/**", "packages/codemode/src/stdlib/**"], - "rules": { - "no-restricted-imports": [ - "error", - { - "paths": [ - { - "name": "effect", - "allowTypeImports": true, - "message": "The evaluator and built-ins are plain generators driven by the job queue in runner.ts. Start host work with runner.host or block on it with runner.blocking; only runner.ts, execute.ts, and extensions.ts run Effects." - } - ] - } - ] - } - }, - { - "files": [ - "packages/codemode/src/interpreter/runner.ts", - "packages/codemode/src/interpreter/execute.ts", - "packages/codemode/src/interpreter/extensions.ts" - ], - "rules": { - "no-restricted-imports": "off" - } } ], "ignorePatterns": [ diff --git a/CHANGELOG.md b/CHANGELOG.md index 97ec79f8002d..37fb38b23598 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,41 @@ Release notes for OpenCode V2, newest first. +## v2.3.2-shuv.1 — 2026-11-20 + +Syncs upstream `dev` through `a96327d3e8`: 104 commits beyond the dev pin in [#508](https://github.com/shuv1337/shuvcode/pull/508), or 159 dev commits plus the v2.3.2 release since v2.3.1. + +### Highlights + +- **New terminal designs and theme names.** The new OpenCode theme is now `opencode`, and the previous one is `opencode-classic`. Night Owl remains Shuvcode's default. +- **Code Mode scripts** run on the psychoscript engine and get a two-minute foreground window before continuing in the background. +- **Background work** appears as running work in the session, rather than looking finished while it is still active. +- **Browser pane tools** gain clearer waits, file previews and safeguards for agent actions. +- **Antigravity Gemini 4 Neon** is available on plans that include it. + +### Breaking changes + +- Code Mode session tools move to `tools.shuvcode.session.rename` and `tools.shuvcode.session.move`. The direct names (`shuvcode_session_rename`, `shuvcode_session_move`) and permission actions are unchanged. + +### Fork changes since v2.3.1-shuv.1 + +- Antigravity fails once rather than retrying a 429 on nearly unused quota ([#503](https://github.com/shuv1337/shuvcode/pull/503)); Gemini 4 Neon was added in [#507](https://github.com/shuv1337/shuvcode/pull/507). +- Model-facing tool namespaces and prompts use Shuvcode ([#504](https://github.com/shuv1337/shuvcode/pull/504)). +- The npm release pipeline gates platform packages before publishing the top-level CLI ([#506](https://github.com/shuv1337/shuvcode/pull/506)). +- Preserves Night Owl, browser status and reconnect grace (only unretrieved commands may replay), root-family permission prompts ([#429](https://github.com/shuv1337/shuvcode/pull/429)) and the hidden Claude Agent SDK provider. + +### Behavior and migration + +- The server no longer waits up to five seconds for managed-policy plugins (`ce7b4252d8`, included in #508). A cold Location may briefly list providers that policy will deny once the plugin loads. +- `full_codemode` defaults on only in local/dev, not in release builds. When enabled, it hides `glob`, `grep` and `webfetch`. +- Session parts are written to `session_part` by default; opt out with `experimental.part_rows: false`. This sync adds the additive machine and machine-key migrations. SQLite full-text search remains opt-in (`sqlite_fts`). +- The TUI uses OpenTUI 0.9.4. Model context uses `` and `` for updates and completed background work. +- Use `browser.tabs.open({ path })` instead of `browser.preview`. An unavailable browser now reports `[browser.not_attached]`; `[browser.disconnected]` still means the connection closed mid-call. + +### Rollback + +Roll back to `v2.3.1-shuv.4`, which already reads `session_part` rows and ignores the additive machine tables. No `v2.3.1-shuv.*` build can decode persisted `Job.Recovery` rows with `kind: "video"`: let video jobs finish or cancel them before rolling back. + ## v2.3.2 — 2026-11-18 ### Highlights diff --git a/bun.lock b/bun.lock index 3d360bedf0ba..ee85d1af4bc9 100644 --- a/bun.lock +++ b/bun.lock @@ -137,7 +137,7 @@ }, "packages/cli": { "name": "shuvcode", - "version": "2.3.1-shuv.1", + "version": "2.3.2-shuv.1", "bin": { "shuvcode": "./bin/shuvcode.mjs", }, @@ -231,6 +231,7 @@ "dependencies": { "acorn": "8.15.0", "effect": "catalog:", + "psychoscript": "0.1.2", }, "devDependencies": { "@tsconfig/bun": "catalog:", @@ -381,6 +382,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": { @@ -464,10 +466,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", @@ -597,8 +601,8 @@ }, "peerDependencies": { "@opencode/theme": "workspace:*", - "@opentui/core": ">=0.8.4", - "@opentui/solid": ">=0.8.4", + "@opentui/core": ">=0.9.4", + "@opentui/solid": ">=0.9.4", "electron": "*", "solid-js": ">=1.9.0", "vite": ">=6", @@ -620,6 +624,7 @@ "dependencies": { "@opencode/plugin": "workspace:*", "@opencode/schema": "workspace:*", + "@opencode/util": "workspace:*", "effect": "catalog:", }, "devDependencies": { @@ -1105,9 +1110,9 @@ "@lydell/node-pty": "1.2.0-beta.12", "@npmcli/arborist": "9.4.0", "@octokit/rest": "22.0.0", - "@opentui/core": "0.8.4", - "@opentui/keymap": "0.8.4", - "@opentui/solid": "0.8.4", + "@opentui/core": "0.9.4", + "@opentui/keymap": "0.9.4", + "@opentui/solid": "0.9.4", "@pierre/diffs": "1.6.1", "@pierre/highlights": "0.2.0", "@playwright/test": "1.60.0", @@ -1981,27 +1986,27 @@ "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="], - "@opentui/core": ["@opentui/core@0.8.4", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.8.4", "@opentui/core-darwin-x64": "0.8.4", "@opentui/core-linux-arm64": "0.8.4", "@opentui/core-linux-arm64-musl": "0.8.4", "@opentui/core-linux-x64": "0.8.4", "@opentui/core-linux-x64-musl": "0.8.4", "@opentui/core-win32-arm64": "0.8.4", "@opentui/core-win32-x64": "0.8.4" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-s2z2FFEWxsQ6IPVEiAjlHHY5yssnCI+dIltL54+ZhVz1EWxylaB0HER+ypPL2goot0DKwKqrM57rnomh19/2rQ=="], + "@opentui/core": ["@opentui/core@0.9.4", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "string-width": "7.2.0" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.9.4", "@opentui/core-darwin-x64": "0.9.4", "@opentui/core-linux-arm64": "0.9.4", "@opentui/core-linux-arm64-musl": "0.9.4", "@opentui/core-linux-x64": "0.9.4", "@opentui/core-linux-x64-musl": "0.9.4", "@opentui/core-win32-arm64": "0.9.4", "@opentui/core-win32-x64": "0.9.4" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-jV8ZAkI87juANCq6XD6UDMp3/WzNpfxloejmdwfCA9UaxBghVkqzoS8RyEYnXDUaS9u+DTCYy1RQMXc1UVibjQ=="], - "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.8.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-kAWCmLsGuxQANeq4AjjX0Yodca2VIofQGUfIH9Edg9BKajYpf941heZfMJkkkJUXawYTNFTR2lBYsdneUUJBrg=="], + "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.9.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-hwQBFr+YSjQ7jxfsLj7AVa1het5veMLfRPFmH1z6eLNlvukdfFA7R4Jl1lHFm3ip5RZRGTanFQDaShOw2l0DMw=="], - "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.8.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-0S62YHtIh1Q9tTun7065njEtYUUtf1zXwllDKXr63R1cVgq+8eRdVQ2PsAGNOqB5OYYno+M8o2tuK/Es2uvmBA=="], + "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.9.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-aBZAjQovTrP/EIsWJb/WXHFzz5Oh+MdOpojNCb567eBVtIRY3W6e/60qwZVgovu7wZcdYbtKYPkuS7+Hh+OGdA=="], - "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.8.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-VGnBN3ItBwZog109wtPIou8pn93TseZwA5OZ05X2PYIYPw+IC6mVeO2Dn0qwwozLBDxeyH3ydbHMFlwzS4/fLg=="], + "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.9.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-/igVllJGl12d9TXI4I8AZ4NFA1wGLwm8If6r+wtnd2Yq3LrZsuEf6MZ836XTnQJHJKNR2QY5TwkLSQg/Qslx5w=="], - "@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.8.4", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-IG887NHjPJEw5D1dvNl9jPbcwNFREFKj2fnqEjdrwCnDRywtjNL7k7GgTo24NNlyMAZAq0OkoM0M0Sn6ex/Adg=="], + "@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.9.4", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-qUOnjER4CY0I4GJc9X0KyNYaxtgUSf/yy+3NwdvOZODbvLMeGyBDQ3209K2iuyfc8c1WU93J5cIXqJj+k18hIw=="], - "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.8.4", "", { "os": "linux", "cpu": "x64" }, "sha512-N/uxyaPpWkCZlDXz3fgHMfMuj1L3IVZ/xZ4JifUc4NW9bwa/CYWFJ5J5jBoy2QsAIqoqo8/OD3iFpXR4o12mNQ=="], + "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.9.4", "", { "os": "linux", "cpu": "x64" }, "sha512-6jKg9AkJ1g3d4n1I8Ug09PouzWBD+FZWhmMEduiULiA0lbYjZL22Y07nfMOSzx/Ehqt/GcY5q8m0V/rK/QWlcQ=="], - "@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.8.4", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-FAiH7wMt/ZbpP2w6TL62deNExTg5w6mujKUBSK89+gJV8FN4jk/K2xz9f522aYhC6SdbpyIKwS0oGIJldYLkcg=="], + "@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.9.4", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-0xjtikRbFJlV33zvtiMhvL90ZlugFV0YWrx07GFoRvUdADxVtB9YSQFjfkdsavZLbc3snd86Qsus6BBAcHg0MA=="], - "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.8.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-vjDuuIcmanoipIKdME8A7ZuBgIw2E1fv4pRJp6M19+Zfx0HIUmtA8bv+mT/kaz8Cpad9EUzJkNI5fV8P2p/iKg=="], + "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.9.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-rLXIEoQBh9tUzTwf79TSRbpC94wtIyUOwRp2CykcgB8m57wM73I9fGKsWEip4scyUkybOH97XvGD/mWZF9ftzA=="], - "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.8.4", "", { "os": "win32", "cpu": "x64" }, "sha512-I4XnzUmyKCb8cRD1UntQXRkIEl0fxfQnzS3bTODWbENAOdRsK2c7Ff07DG2qTAqNijyTuk63C+uLmAT9ObOQ1Q=="], + "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.9.4", "", { "os": "win32", "cpu": "x64" }, "sha512-pZVlwwJZ3VqOjN/fmVFwaLA1H8JNOvuW27DoXzOIBDxoMi+l1UsL6rHGsLRDSPssQ3pjSn/jFCWo+xD/EtcbAA=="], - "@opentui/keymap": ["@opentui/keymap@0.8.4", "", { "dependencies": { "@opentui/core": "0.8.4" }, "peerDependencies": { "@opentui/react": "0.8.4", "@opentui/solid": "0.8.4", "react": ">=19.2.0", "solid-js": "^1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-dOHQYgvToXsYr4Am44wBEhvSvaF2bqZfJM8xPhEEZlpcnww3/+eh3OEq30btAKcukIMxDH0dI5cyCUfF2/8yUw=="], + "@opentui/keymap": ["@opentui/keymap@0.9.4", "", { "dependencies": { "@opentui/core": "0.9.4" }, "peerDependencies": { "@opentui/react": "0.9.4", "@opentui/solid": "0.9.4", "react": ">=19.2.0", "solid-js": "^1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-T2SSIT1p9Ex8O5eLp9g8Ou0z0wR3xeDg/70xz5RS++xksdXtZI7KS66QN0XXQmo86Quos7qwiiJdsSXUQNSwnQ=="], - "@opentui/solid": ["@opentui/solid@0.8.4", "", { "dependencies": { "@babel/core": "7.29.7", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.8.4", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.16", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "^1.9.12" } }, "sha512-QyaWIAtZTaAdYJiP4K2cG6hbXQkNUBfa0hjYQwvvr/V2OFIZWZ7l+SP8CYM05lBqVDfOraeThvSrhX+IuvKySA=="], + "@opentui/solid": ["@opentui/solid@0.9.4", "", { "dependencies": { "@babel/core": "7.29.7", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.9.4", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.16", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "^1.9.12" } }, "sha512-dTX+7qlxm8+/YoKL09pGMGfTPVYnnwIIhxL4+q84Zrh2atqJ+4Xx1xeRoqjVkdGUDOIt1WrLkT9VWQ9A30fYNA=="], "@opentunnel/client": ["@opentunnel/client@0.6.1", "", { "dependencies": { "@opentunnel/protocol": "0.6.1" }, "peerDependencies": { "effect": "^4.0.0", "undici": ">=7.0.0" }, "optionalPeers": ["undici"] }, "sha512-OuVNlWywQebIXCtkixjVHebOsR3KFRxJ0DSZry6Dzj4hHaHIf3eTVmQ7VwLCjuVmw+ctU2qHIP6RxuAPr07WDw=="], @@ -3953,6 +3958,8 @@ "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], + "psychoscript": ["psychoscript@0.1.2", "", { "dependencies": { "acorn": "8.15.0" }, "peerDependencies": { "effect": "^4.1.0" } }, "sha512-eEuVbhaQ+3MEfi+LTNatMFY0OWcrmZjiUDd/4KVmWOCBTVYY87QoIc/DPNTDu+GVKHDeAPCsIqDq6wVyLMODXA=="], + "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], "pupa": ["pupa@3.3.0", "", { "dependencies": { "escape-goat": "^4.0.0" } }, "sha512-LjgDO2zPtoXP2wJpDjZrGdojii1uqO0cnwKoIoUzkfS98HDmbeiGmYiXo3lXeFlq2xvne1QFQhwYXSUCLKtEuA=="], @@ -4303,7 +4310,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=="], @@ -4689,8 +4698,6 @@ "@opentui/core/diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], - "@opentui/core/marked": ["marked@17.0.1", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg=="], - "@opentui/solid/babel-preset-solid": ["babel-preset-solid@1.9.16", "", { "dependencies": { "babel-plugin-jsx-dom-expressions": "^0.40.11" }, "peerDependencies": { "@babel/core": "^7.0.0", "solid-js": "^1.9.16" }, "optionalPeers": ["solid-js"] }, "sha512-+0h40Qk2oBfkQ4OGDBHIDtvq/XQiOnCfzjNHmMxriAr8MmdsaIbyJgqYglDs4d70sF8O08sSpx61TKdpUt3oRw=="], "@oxc-parser/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="], @@ -4941,6 +4948,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=="], diff --git a/bunfig.toml b/bunfig.toml index 37e4faf7d744..cfabf2c6b522 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -2,7 +2,7 @@ exact = true # Only install newly resolved package versions published at least 3 days ago. minimumReleaseAge = 259200 -minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@hona/strobe", "@hona/strobe-darwin-arm64", "@hona/strobe-darwin-x64", "@hona/strobe-linux-arm64", "@hona/strobe-linux-x64", "@hona/strobe-win32-arm64", "@hona/strobe-win32-x64", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "@agentclientprotocol/sdk", "opentui-spinner", "bun-types", "typescript@7.1.0-beta", "@textjs/app", "@textjs/core", "@textjs/opencode", "@textjs/react"] +minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@hona/strobe", "@hona/strobe-darwin-arm64", "@hona/strobe-darwin-x64", "@hona/strobe-linux-arm64", "@hona/strobe-linux-x64", "@hona/strobe-win32-arm64", "@hona/strobe-win32-x64", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "@agentclientprotocol/sdk", "opentui-spinner", "bun-types", "typescript@7.1.0-beta", "@textjs/app", "@textjs/core", "@textjs/opencode", "@textjs/react", "psychoscript"] [test] root = "./do-not-run-tests-from-root" diff --git a/docs/sync-2026-11-20-dev.md b/docs/sync-2026-11-20-dev.md new file mode 100644 index 000000000000..505c1cf1b47e --- /dev/null +++ b/docs/sync-2026-11-20-dev.md @@ -0,0 +1,107 @@ +# Upstream dev sync and v2.3.2-shuv.1 prep — 2026-11-20 PST + +## Summary and ancestry + +- Fork base: `3375c4783abe29355d33239ab7ac2d0c43af13ee` (`origin/integration-v2`, #508). +- Previous upstream pin and merge base: `d33b5783338b8b350aafc09f7dc2701eeba52a9a`. +- Merged `a96327d3e84d795cca231dc30b534193bbc0f47b` as `c42e006d05` on `sync-dev-a96327`, with the fork base as first parent. Verified live refs without moving either pin. Live upstream `dev` had moved to `701eff9e26a2503d5758483bf973100d8ee590a6` at preflight; no v2.3.3 tag was present. The v2.3.2 tag was already merged in #508. +- This adds 104 upstream commits past #508, for 159 dev commits plus the v2.3.2 release since v2.3.1. CLI release metadata moves to `2.3.2-shuv.1` separately; the package and bin both remain `shuvcode`. Nothing is published by this PR. + +| Tree comparison | Files | Insertions | Deletions | +| -------------------------------------------------------------------------- | ----: | ---------: | --------: | +| Previous pin → fork base (20,761 fork-side commits in the symmetric range) | 735 | 42,488 | 7,669 | +| Previous pin → pinned dev (104 commits) | 1,230 | 64,558 | 48,561 | +| Pinned dev → fork base (pre-sync divergence) | 1,791 | 90,962 | 72,140 | +| Fork base → merge commit | 1,230 | 64,533 | 49,479 | + +## Conflict resolutions (24 paths) + +The merge commit resolves only these paths. Use `git show --remerge-diff c42e006d05` to review the resolutions. + +| Path | Resolution | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `bunfig.toml` | Retain both fork dependency-age exceptions and append upstream's `psychoscript`. | +| `packages/app/src/providers/connect/dialog.tsx` | Keep the shared `connectPopular` list and take upstream's `providerNote` verbatim. | +| `packages/codemode/test/parity.test.ts` | Accept deletion; the language implementation moved to psychoscript. | +| `packages/core/src/automation/code.ts` | Keep Shuvcode's forbidden-tool namespace with upstream's `session.move` and `session.rename` nesting. | +| `packages/core/src/database/migration.gen.ts` | Retain all existing fork migration registrations, including `m48`; add both machine migrations as `m63` and `m64` in imports and array. | +| `packages/core/src/session/runner/publish-llm-event.ts` | Release hosted activity and clear live tool metadata at both settlement points. | +| `packages/core/src/tool/plugin/opencode.ts` | Use `shuvcode.session` for rename and move, retain pinned move and both worktree hint variants. | +| `packages/core/test/fixtures/recordings/session-runner/openai-chat-streams-text.json` | Take upstream's new system-update and background-result instructions, with `Shuvcode` matching `system.txt`. | +| `packages/core/test/tool-model-policy.test.ts` | Take the upstream DeepSeek direct-tool expectation; keep the fork's synthetic catalog paths. | +| `packages/core/test/tool-opencode.test.ts` | Check `tools.shuvcode.session.move` in Code Mode and keep direct `shuvcode_session_move`. | +| `packages/core/test/video-generation.test.ts` | Take upstream `36bd410cad` verbatim; retire the #508 video-clock carry. | +| `packages/plugin-browser/src/connection.ts` | Keep fork replay, retrieval tracking, status/waiting/retired accessors; take upstream owned grants, stale-grant reconciliation, deny-first `refuse`, `authorize`, evaluation hook and child-grant stripping. Remove `require`. | +| `packages/plugin-browser/src/machine.ts` | Keep parked commands, retirement and reconnect grace; take grant/rule/session selectors and structured failure codes. Return unprefixed detached guidance with Shuvgeist/status; retain `[browser.disconnected]` for mid-call drops. | +| `packages/plugin-browser/src/skill.ts` | Take upstream snapshot, evaluate, wait and path-preview guidance; use Shuvcode wording and keep one status/Shuvgeist note. | +| `packages/plugin-browser/src/tools.ts` | Take `refuse` → parse → `authorize` → wait/show/target with aliases; keep pinned `browser.status` and its schema. | +| `packages/plugin-browser/test/connection.test.ts` | Take the upstream grant/refusal/upload suite verbatim; preserve the fork suite in `connection-replay.test.ts` in the follow-up. | +| `packages/plugin-browser/test/rpc.test.ts` | Keep `Result`, `Schema`, `Session` and `Browser` imports. | +| `packages/tui/src/component/prompt/index.tsx` | Keep upstream's `same()` array guards and compare the optional terminal attachment by identity, not as a list. | +| `packages/tui/src/context/theme.tsx` | Resolve upstream aliases first, then fall back to Night Owl. | +| `packages/tui/src/plugin/context.tsx` | Keep OpenTUI 0.9's `renderBlock` and fork autocomplete. | +| `packages/tui/src/theme/index.ts` | Keep `DEFAULT_THEME_NAME` and import upstream's `opencode-classic`. | +| `packages/tui/test/app-lifecycle.test.tsx` | Take upstream `e3ee082167` verbatim; retire the old fork test carry. | +| `packages/tui/test/component/go-upsell-art.test.tsx` | Keep Shuvcode glyphs and the upstream manual-clock 30 fps check. | +| `packages/tui/test/context/theme.test.tsx` | Take upstream's theme tests verbatim. | + +## Semantic follow-ups + +- Updated namespace, automation, external-directory and worktree-hint assertions. The synthetic `opencode.session` registry fixture remains unchanged by the follow-ups. Actual Code Mode paths changed, but direct tool names and permission actions did not. +- Reordered connect providers to put Go before Console, keeping Claude Agent excluded. +- Removed the Claude folder worker from the CLI bundle entrypoints, not from disk. +- The new CLI log-redaction tests initially looked under `data/opencode`. The same isolated CLI invocation on `3375c4783a` also logs under `data/shuvcode` (`data/opencode` returns `ENOENT`). The fixture now uses `Global.app` without changing its redaction assertions. +- Adapted the fork browser fixture to owned grants and the upstream permission hooks. Detached operations now test `[browser.not_attached]`, while dropped commands test `[browser.disconnected]`. Added an independent replay check for an unretrieved `wait` command with a newly published tab generation. +- Restored compatibility with upstream prompt extmark data for optional terminal attachments. Kept the lifecycle suite byte-for-byte upstream in the merge, then retargeted just its epilogue command assertion from `opencode` to `shuvcode`: the merged upstream assertion failed on the fork binary name, and the same test passed on `3375c4783a`. +- Made the dialog-select cursor fixture request `opencode-classic` explicitly, the theme it was already using to compute its expected color. The base fixture passed before the theme rename. +- Ran the client generator; it made no additional changes, so there is no client-generation commit. + +## Fork preservation and flags + +- Claude Agent SDK three-layer audit: `ProviderPlugins` does not load it; config rejects both hidden IDs; the same 17 files reference `isHiddenProvider`, with zero `claudeAgent` i18n keys. The build does not bundle the Claude folder worker. The worker and provider implementation remain on disk, and the provider tree has no follow-up changes beyond the upstream merge. +- The #429 root-family permission routing, child waiting banner and claim-before-yield (`pending.delete(id)`) remain. Browser reconnect retains the single-replay rule for unretrieved commands, and retirement suppresses replay after delete/move. +- `Global.app`, ports `0x1337`/`0x1338`, npm-only updates, #506 publish gating and the bundled Antigravity/Claude/quota plugins remain in place. +- `onByDefault` is strictly `local` or `dev`; `integration-v2` and release channels do not get `full_codemode` by default. `todo` and `sqlite_fts` are opt-in even in dev. The TUI's separate new-designs default is on; Night Owl remains the fork theme default. +- The upstream removal of the managed-policy plugin startup wait (`ce7b4252d8`, already in #508) still applies. A cold Location can briefly list providers that the policy denies once loaded; client refresh behavior is unchanged by this sync. +- Machine and machine-key migrations are additive. `session_part` writes now default on; `experimental.part_rows: false` opts out. For rollback, use `v2.3.1-shuv.4`, after finishing or cancelling any video jobs whose persisted recovery kind the old version cannot decode. + +## Branch inventory + +Zero new unmerged fork branches at preflight; no open fork PRs. `antigravity-no-retry` stays at `c3cca2efc9` (an obsolete artifact-heavy carry; intended changes landed in #503/#504). `pwsh-hosted-probe` (`174302ace9`) and `pwsh-ci-diag` (`fb789a630a`) remain parked diagnostics for #493. All other prior dispositions remain as recorded in [the #508 audit](sync-2026-11-19-v2.3.2-dev.md) and its predecessors. No branch was deleted. + +## Validation + +On `shuvdev` with Bun 1.4.4: `nice -n 19`, clean `env -i`, canonical private HOME/XDG/TMPDIR, Turbo concurrency 3 and sequential full package runs. GitHub-hosted CI is the full cross-platform gate. + +| Gate | Result | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Conflict markers, whitespace, namespace and hidden-provider scans | Pass; zero stale runtime namespaces or Claude Agent translation keys; 17 hidden-provider reference files on both pins | +| `bun install --frozen-lockfile` | Pass after the merge and release bump; release-prep install made no changes | +| `bun run migration --check` (`packages/core`) | Pass; no schema drift | +| `bun run generate` (`packages/client`) | Pass; no generated diff | +| Root `bun run check` | Pass, 40/40 tasks | +| Focused core, including session replay, permissions, Jev, Antigravity and process-death recovery | 344 pass | +| Core (full suite) | 8,022 pass, 16 skip, 11 GitLab OAuth failures. All 11 reproduced on `3375c4783a`; port 8080 is occupied on `shuvdev`. | +| Video jobs | 20 pass over ten repetitions of the two upstream tests | +| TUI | Full initial run: 1,794 pass, 2 skip, 1 cursor-fixture failure. After updating the fixture: 141 focused tests passed, including lifecycle, cursor, Night Owl, and the `[90, 6]` manual-clock art check. | +| CLI | Full initial run: 514 pass, 7 skip, 3 log-redaction fixture path failures. All three passed after the fixture fix. The launcher suite passed with canonical private paths. | +| Server / AI | 144 pass, 1 skip / 2,306 pass, 29 skip | +| Schema / Protocol / Util / Plugin / Client | 95 / 14 / 156 / 38 / 279 pass | +| App unit / browser | 2,843 / 378 pass | +| App built e2e (focused) | 138 pass across home, settings, session header, and subagent child navigation; four workers using existing system Chromium | +| Session UI | 621 pass | +| Browser plugin (full suite) | 204 pass, including 21 fork replay/preflight tests | +| Code Mode (full suite) | 322 pass; language parity tests now live with psychoscript | +| Antigravity / Claude / Quota plugins | 90 / 43 / 37 pass | +| CI Effect simplification rule tests and lint | Pass | +| Official TypeScript compiler (core, browser plugin, app) | Pass | + +The `chore(sync)` title gates `unit` and `e2e`; `typecheck` runs separately. No merge, publish, tag, or deploy was performed. + +## Rat-stack pages followed + +- [`a-browser-send-follows-one-path`](https://ratstack.sh/lore/a-browser-send-follows-one-path): retain a single authorization path before dispatch. +- [`scopes-own-resources`](https://ratstack.sh/lore/scopes-own-resources): settle hosted activity and live metadata with the tool call. +- [`concurrent-work-needs-an-owner`](https://ratstack.sh/lore/concurrent-work-needs-an-owner): preserve scoped replay work and keep validation jobs bounded. +- [`testing-ladder`](https://ratstack.sh/lore/testing-ladder): start with structural and focused checks; use the package suites and CI for integration coverage. +- [`investigate-a-failure`](https://ratstack.sh/skills/investigate-a-failure): compare unexpected failures against the pinned fork base before dispositioning. diff --git a/flake.lock b/flake.lock index 021f274baab6..d20625aa3081 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1790510107, - "narHash": "sha256-EVMNYv7hYDDD9TGVT/hIyTYgpiXA8y3m5xIEIxuGNU0=", + "lastModified": 1794840529, + "narHash": "sha256-ySrWnmZB5UsZTYGHHnBjllT05O5iFjElCRS+mabtfP0=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "3181085bfd08663b6b9e60bc7a8395c2aaa741bd", + "rev": "e21fec321d73511849707a7585e4ea155ee4bf40", "type": "github" }, "original": { diff --git a/package.json b/package.json index 4474349dc21c..16dcd00db98d 100644 --- a/package.json +++ b/package.json @@ -51,9 +51,9 @@ "@hona/strobe": "0.42.0", "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", - "@opentui/core": "0.8.4", - "@opentui/keymap": "0.8.4", - "@opentui/solid": "0.8.4", + "@opentui/core": "0.9.4", + "@opentui/keymap": "0.9.4", + "@opentui/solid": "0.9.4", "@tanstack/solid-virtual": "3.13.37", "@standard-schema/spec": "1.1.0", "@kobalte/core": "0.13.13", diff --git a/packages/ai/src/protocols/gemini.ts b/packages/ai/src/protocols/gemini.ts index 330749340b8c..b34dbdaf1fcb 100644 --- a/packages/ai/src/protocols/gemini.ts +++ b/packages/ai/src/protocols/gemini.ts @@ -149,25 +149,6 @@ const GeminiThinkingConfig = Schema.Struct({ thinkingLevel: Schema.optional(GeminiThinkingLevel), }) -const GeminiSafetySetting = Schema.Struct({ - category: knownString< - | "HARM_CATEGORY_UNSPECIFIED" - | "HARM_CATEGORY_HATE_SPEECH" - | "HARM_CATEGORY_DANGEROUS_CONTENT" - | "HARM_CATEGORY_HARASSMENT" - | "HARM_CATEGORY_SEXUALLY_EXPLICIT" - | "HARM_CATEGORY_CIVIC_INTEGRITY" - >(), - threshold: knownString< - | "HARM_BLOCK_THRESHOLD_UNSPECIFIED" - | "BLOCK_LOW_AND_ABOVE" - | "BLOCK_MEDIUM_AND_ABOVE" - | "BLOCK_ONLY_HIGH" - | "BLOCK_NONE" - | "OFF" - >(), -}) - // ============================================================================= // Provider Options // ============================================================================= @@ -180,7 +161,7 @@ const GeminiThinkingConfigInput = Schema.Struct({ }) const Options = Schema.Struct({ cachedContent: lenient(Schema.String), - safetySettings: lenient(Schema.Array(GeminiSafetySetting)), + safetySettings: lenient(Schema.Array(GeminiGenerateContent.SafetySetting)), serviceTier: lenient(knownString<"standard" | "flex" | "priority">()), thinkingConfig: lenient(GeminiThinkingConfigInput), }) @@ -202,7 +183,7 @@ const GeminiBodyFields = { cachedContent: Schema.optional(Schema.String), contents: Schema.Array(GeminiContent), labels: Schema.optional(Schema.Record(Schema.String, Schema.String)), - safetySettings: optionalArray(GeminiSafetySetting), + safetySettings: optionalArray(GeminiGenerateContent.SafetySetting), serviceTier: Schema.optional(Schema.String), systemInstruction: Schema.optional(GeminiSystemInstruction), tools: optionalArray(GeminiTool), diff --git a/packages/ai/src/protocols/google-interactions.ts b/packages/ai/src/protocols/google-interactions.ts index 8bd815accf7f..8d1665520dd2 100644 --- a/packages/ai/src/protocols/google-interactions.ts +++ b/packages/ai/src/protocols/google-interactions.ts @@ -1,9 +1,14 @@ -import { Effect, Option, Schema, SchemaGetter } from "effect" +import { Effect, Option, Schema, SchemaGetter, Stream } from "effect" import { Route } from "../route/client.js" import { Auth } from "../route/auth.js" import { Endpoint } from "../route/endpoint.js" -import { Framing } from "../route/framing.js" import { Protocol } from "../route/protocol.js" +import { + HttpTransport, + type Transport, + type TransportExecution, + type TransportPrepareInput, +} from "../route/transport/index.js" import { AIError, ContentPolicyError, @@ -25,6 +30,9 @@ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js" import { ToolStream } from "./utils/tool-stream.js" const ADAPTER = "google-interactions" +const CONTINUATION = "requires_continuation" +// Matches Google's GenAI SDKs (Python, JS, and Go). +const MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS = 3 const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator" export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta" @@ -38,6 +46,7 @@ const Options = Schema.Struct({ thinkingLevel: lenient(ThinkingLevel), thinkingSummaries: lenient(knownString<"auto" | "none">()), serviceTier: lenient(knownString<"standard" | "flex" | "priority" | "deferred">()), + safetySettings: lenient(Schema.Array(GeminiGenerateContent.SafetySetting)), }) export type OptionsInput = typeof Options.Encoded export type ProviderOptionsInput = OptionsInput @@ -83,12 +92,14 @@ const ToolChoice = Schema.Union([ ]) const Body = Schema.Struct({ model: Schema.String, - input: Schema.Array(InputStep), + input: Schema.optional(Schema.Array(InputStep)), stream: Schema.Literal(true), store: Schema.Boolean, previous_interaction_id: Schema.optional(Schema.String), + continuation_token: Schema.optional(Schema.String), system_instruction: Schema.optional(Schema.String), service_tier: Schema.optional(Schema.String), + safety_settings: Schema.optional(Schema.Array(Schema.Struct({ type: Schema.String, threshold: Schema.String }))), tools: Schema.optional( Schema.Array( Schema.Struct({ @@ -157,6 +168,7 @@ const Interaction = Schema.StructWithRest( Schema.Struct({ id: Schema.optional(Schema.String), status: Schema.String, + continuation_token: optionalNull(Schema.String), usage: Schema.optional(RawUsage), errors: Schema.optional( Schema.Array(Schema.Struct({ code: Schema.optional(Schema.String), message: Schema.optional(Schema.String) })), @@ -202,6 +214,8 @@ const Event = Schema.Union([ event_type: Schema.Literal("interaction.status_update"), interaction_id: Schema.optional(Schema.String), status: Schema.String, + continuation_token: optionalNull(Schema.String), + usage: Schema.optional(RawUsage), }), Schema.Struct({ event_type: Schema.Literal("interaction.completed"), interaction: Interaction }), Schema.Struct({ event_type: Schema.Literal("error"), error: Schema.optionalKey(Schema.Unknown) }), @@ -216,6 +230,10 @@ interface ParserState { readonly route: string readonly metadataKey: string readonly lifecycle: Lifecycle.State + readonly hop: number + readonly hasToolCalls: boolean + readonly usage?: RawUsage + readonly continuedUsage: ReadonlyArray readonly steps: Partial> readonly tools: ToolStream.State } @@ -224,13 +242,28 @@ type StepResult = readonly [ParserState, ReadonlyArray] // ============================================================================= // Request Body Construction // ============================================================================= +// https://aistudio.google.com/docs/document-processing#office-documents +const OFFICE_DOCUMENT_MIME_TYPES = new Set([ + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.wordprocessingml.template", + "application/vnd.oasis.opendocument.text", + "application/vnd.ms-powerpoint", + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "application/vnd.oasis.opendocument.presentation", + "application/vnd.ms-excel", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.oasis.opendocument.spreadsheet", +]) + export const mediaContent = Effect.fnUntraced(function* (asset: Media.Asset) { if ( asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video" && asset.mediaType !== "application/pdf" && - asset.mediaType !== "text/csv" + asset.mediaType !== "text/csv" && + !OFFICE_DOCUMENT_MIME_TYPES.has(asset.mediaType) ) return yield* ProviderShared.invalidRequest( `Google Interactions does not support ${asset.mediaType} document input`, @@ -360,6 +393,10 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque previous_interaction_id: options.previousInteractionId, system_instruction: request.system.length ? ProviderShared.joinText(request.system) : undefined, service_tier: options.serviceTier, + safety_settings: options.safetySettings?.map((setting) => ({ + type: setting.category.replace(/^HARM_CATEGORY_/, "").toLowerCase(), + threshold: setting.threshold.toLowerCase(), + })), tools: flattened.tools.length ? flattened.tools.map((tool) => ({ type: "function" as const, @@ -387,32 +424,54 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque const metadata = (state: ParserState, step: OutputStep): ProviderMetadata => ({ [state.metadataKey]: { interactionSignature: step.signature }, }) -const mapUsage = (usage: RawUsage | undefined, key: string) => { - if (!usage) return undefined - const input = usage.total_input_tokens ?? undefined - const cached = usage.total_cached_tokens ?? undefined - const reasoning = usage.total_thought_tokens ?? undefined - const output = - usage.total_output_tokens === undefined || usage.total_output_tokens === null +const mapUsage = (usage: RawUsage | undefined, key: string, continued: ParserState["continuedUsage"]) => { + if (!usage && continued.every((hop) => !hop)) return undefined + const first = continued.length ? continued[0] : usage + const hops = [...continued, usage] + const sum = (field: (hop: RawUsage) => number | null | undefined) => + ProviderShared.sumTokens(...hops.map((hop) => (hop ? (field(hop) ?? undefined) : undefined))) + const input = first?.total_input_tokens ?? undefined + const cached = first?.total_cached_tokens ?? undefined + const reasoning = sum((hop) => hop.total_thought_tokens) + const text = sum((hop) => hop.total_output_tokens) + const output = continued.length + ? ProviderShared.sumTokens(text, reasoning) + : text === undefined ? undefined - : usage.total_output_tokens + (reasoning ?? 0) + : text + (reasoning ?? 0) return new Usage({ - contextTokens: usage.raw_prompt_token ?? input, + contextTokens: first?.raw_prompt_token ?? input, inputTokens: input, outputTokens: output, nonCachedInputTokens: ProviderShared.subtractTokens(input, cached), cacheReadInputTokens: cached, reasoningTokens: reasoning, - totalTokens: usage.total_tokens ?? undefined, - providerMetadata: { [key]: usage }, + totalTokens: continued.length + ? ProviderShared.totalTokens(input, output, undefined) + : (usage?.total_tokens ?? undefined), + // Keep re-billed input in provider metadata, separate from the logical call's input. + providerMetadata: { + [key]: continued.length + ? { + total_input_tokens: sum((hop) => hop.total_input_tokens), + total_cached_tokens: sum((hop) => hop.total_cached_tokens), + total_output_tokens: text, + total_thought_tokens: reasoning, + total_tokens: sum((hop) => hop.total_tokens), + requests: hops.length, + } + : (usage ?? {}), + }, }) } +const blockID = (state: ParserState, index: number) => (state.hop === 0 ? String(index) : `${state.hop}:${index}`) + const onStart = Effect.fnUntraced(function* (state: ParserState, index: number, step: OutputStep) { const events: LLMEvent[] = [] let lifecycle = Lifecycle.stepStart(state.lifecycle, events) let tools = state.tools - const id = String(index) + const id = blockID(state, index) if (step.type === "thought") { lifecycle = Lifecycle.reasoningStart(lifecycle, events, id, metadata(state, step)) for (const part of step.summary ?? []) lifecycle = Lifecycle.reasoningDelta(lifecycle, events, id, part.text) @@ -439,7 +498,16 @@ const onStart = Effect.fnUntraced(function* (state: ParserState, index: number, events.push(LLMEvent.toolInputStart({ id: step.id, name: step.name, providerMetadata: metadata(state, step) })) } else return yield* ProviderShared.eventError(ADAPTER, `Unsupported Interactions step: ${step.type}`, encodeJson(step)) - return [{ ...state, lifecycle, tools, steps: { ...state.steps, [index]: step } }, events] satisfies StepResult + return [ + { + ...state, + lifecycle, + tools, + hasToolCalls: state.hasToolCalls || step.type === "function_call", + steps: { ...state.steps, [index]: step }, + }, + events, + ] satisfies StepResult }) const onDelta = Effect.fnUntraced(function* (state: ParserState, index: number, delta: typeof Delta.Type) { @@ -449,12 +517,15 @@ const onDelta = Effect.fnUntraced(function* (state: ParserState, index: number, const events: LLMEvent[] = [] if (delta.type === "text" && step.type === "model_output") return [ - { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, String(index), delta.text) }, + { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, blockID(state, index), delta.text) }, events, ] satisfies StepResult if (delta.type === "thought_summary" && step.type === "thought") return [ - { ...state, lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, String(index), delta.content.text) }, + { + ...state, + lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, blockID(state, index), delta.content.text), + }, events, ] satisfies StepResult if (delta.type === "thought_signature") { @@ -493,12 +564,15 @@ const onStop = Effect.fnUntraced(function* (state: ParserState, index: number) { const events: LLMEvent[] = [] if (step.type === "thought") return [ - { ...state, lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, String(index), metadata(state, step)) }, + { + ...state, + lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, blockID(state, index), metadata(state, step)), + }, events, ] satisfies StepResult if (step.type === "model_output") return [ - { ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, String(index)) }, + { ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, blockID(state, index)) }, events, ] satisfies StepResult const result = yield* ToolStream.finish(ADAPTER, state.tools, index) @@ -524,7 +598,32 @@ const failureReason = (route: string, code: string | undefined, message: string, return classifyProviderFailure({ message, data, rawBody }) } -const step = Effect.fnUntraced(function* (state: ParserState, event: Event) { +// Marks a request boundary without adding another logical LLM step or finish. +class NextRequest {} + +const step = Effect.fnUntraced(function* (state: ParserState, event: Event | NextRequest) { + if (event instanceof NextRequest) { + const pending = yield* ToolStream.finishAll(ADAPTER, state.tools) + const events = [...pending.events] + let lifecycle = state.lifecycle + for (const [index, step] of Object.entries(state.steps)) { + const id = blockID(state, Number(index)) + if (step?.type === "thought") lifecycle = Lifecycle.reasoningEnd(lifecycle, events, id, metadata(state, step)) + if (step?.type === "model_output") lifecycle = Lifecycle.textEnd(lifecycle, events, id) + } + return [ + { + ...state, + hop: state.hop + 1, + lifecycle, + steps: {}, + tools: ToolStream.empty(), + usage: undefined, + continuedUsage: [...state.continuedUsage, state.usage], + }, + events, + ] satisfies StepResult + } switch (event.event_type) { case "step.start": return yield* onStart(state, event.index, event.step) @@ -532,8 +631,9 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) { return yield* onDelta(state, event.index, event.delta) case "step.stop": return yield* onStop(state, event.index) - case "interaction.created": case "interaction.status_update": + return [{ ...state, usage: event.usage ?? state.usage }, []] satisfies StepResult + case "interaction.created": case "unknown": return [state, []] satisfies StepResult case "error": { @@ -551,6 +651,8 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) { } case "interaction.completed": { const interaction = event.interaction + if (interaction.status === CONTINUATION) + return [{ ...state, usage: interaction.usage ?? state.usage }, []] satisfies StepResult if (interaction.status === "failed" || interaction.status === "cancelled") { const messages = (interaction.errors ?? []).flatMap((error) => (error.message?.trim() ? [error.message] : [])) const coded = interaction.errors?.find((error) => error.code) @@ -573,18 +675,17 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) { ) const pending = yield* ToolStream.finishAll(ADAPTER, state.tools) const events = [...pending.events] - const hasToolCalls = Object.values(state.steps).some((item) => item?.type === "function_call") const lifecycle = Lifecycle.finish(state.lifecycle, events, { reason: { normalized: - interaction.status === "requires_action" || (interaction.status === "completed" && hasToolCalls) + interaction.status === "requires_action" || (interaction.status === "completed" && state.hasToolCalls) ? "tool-calls" : interaction.status === "incomplete" ? "length" : "stop", raw: interaction.status, }, - usage: mapUsage(interaction.usage, state.metadataKey), + usage: mapUsage(interaction.usage ?? state.usage, state.metadataKey, state.continuedUsage), providerMetadata: { [state.metadataKey]: { interactionId: interaction.id } }, }) return [{ ...state, lifecycle, tools: pending.tools }, events] satisfies StepResult @@ -592,6 +693,177 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) { } }) +// ============================================================================= +// Transport +// ============================================================================= +type Body = typeof Body.Type +export interface Prepared { + readonly http: HttpTransport.HttpPrepared + readonly input: TransportPrepareInput +} + +interface Resume { + readonly token: string + readonly owner?: string + readonly reconnectsWithoutProgress: number + readonly lastError?: AIError +} + +const sse = HttpTransport.sseJson.with() +const WireEvent = Protocol.jsonEvent(Event) +const decodeEvent = Schema.decodeUnknownEffect(WireEvent) + +export const transport: Transport = { + id: sse.id, + prepare: (input) => sse.prepare(input).pipe(Effect.map((http) => ({ http, input }))), + execute: (prepared, request, runtime) => + Effect.gen(function* () { + const label = `${request.model.provider}/${request.model.route.id}` + const raw = new WeakMap() + const respond = ( + execution: TransportExecution, + resume?: Resume, + ): Stream.Stream => + Stream.suspend(() => { + let token = resume?.token + let owner: string | undefined + let status: string | undefined + let contentSinceToken = false + let terminal = false + let dropped: AIError | undefined + const pendingTools = new Set() + return execution.frames.pipe( + Stream.mapEffect((frame) => + decodeEvent(frame).pipe( + Effect.mapError((cause) => + ProviderShared.eventError(ADAPTER, `Invalid ${label} stream event`, frame, cause), + ), + Effect.map((event) => { + raw.set(event, frame) + switch (event.event_type) { + case "interaction.created": + owner = event.interaction.id + break + case "interaction.status_update": + status = event.status + owner = event.interaction_id ?? owner + if (event.continuation_token && event.continuation_token !== token) { + token = event.continuation_token + contentSinceToken = false + } + break + case "interaction.completed": + terminal = true + status = event.interaction.status + owner = event.interaction.id ?? owner + if (event.interaction.continuation_token) { + token = event.interaction.continuation_token + contentSinceToken = false + } + break + case "step.start": + if (event.step.type === "function_call") pendingTools.add(event.index) + if ( + pendingTools.has(event.index) || + event.step.content?.length || + event.step.summary?.length || + event.step.signature + ) + contentSinceToken = true + break + case "step.delta": + contentSinceToken = true + break + case "step.stop": + if (pendingTools.delete(event.index)) contentSinceToken = true + break + } + return event + }), + ), + ), + Stream.takeUntil((event) => event.event_type === "interaction.completed"), + Stream.catchIf( + (error) => error.reason._tag === "Transport" && error.reason.code !== "Timeout", + (error) => { + dropped = error + return Stream.empty + }, + ), + Stream.concat( + Stream.suspend(() => { + const needsContinuation = status === CONTINUATION + const resumable = needsContinuation || (!terminal && (status === undefined || status === "in_progress")) + const newToken = token !== resume?.token + // An interrupted tool call may carry arguments across the checkpoint. Don't finalize it on EOF. + if ( + token && + resumable && + !contentSinceToken && + (terminal || pendingTools.size === 0) && + (!needsContinuation || newToken) + ) { + const reconnectsWithoutProgress = newToken ? 0 : (resume?.reconnectsWithoutProgress ?? 0) + 1 + const lastError = dropped ?? (newToken ? undefined : resume?.lastError) + if (reconnectsWithoutProgress > MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS) { + if (!lastError) return Stream.empty + return Stream.fail( + new AIError({ + reason: new InvalidProviderOutputError({ + route: label, + message: lastError.reason.message, + classification: "incomplete-stream", + cause: lastError, + http: lastError.reason.http, + }), + }), + ) + } + return Stream.concat( + Stream.succeed(new NextRequest()), + next({ token, owner: newToken ? owner : resume?.owner, reconnectsWithoutProgress, lastError }), + ) + } + if (dropped) return Stream.fail(dropped) + if (terminal && needsContinuation && !token) + return Stream.fail(ProviderShared.eventError(label, "Google Interactions continued without a token")) + // No safe checkpoint. Leave EOF for the route's incomplete-stream check. + return Stream.empty + }), + ), + ) + }) + const next = (resume: Resume) => { + const body = prepared.input.body + return Stream.unwrap( + sse + .prepare({ + ...prepared.input, + body: { + ...body, + continuation_token: resume.token, + ...(body.store && resume.owner ? { input: undefined, previous_interaction_id: resume.owner } : {}), + }, + }) + .pipe( + Effect.flatMap((continued) => sse.execute(continued, request, runtime)), + Effect.map((execution) => respond(execution, resume)), + ), + ) + } + const first = yield* sse.execute(prepared.http, request, runtime) + return { + frames: respond(first), + http: first.http, + body: (frame) => raw.get(frame), + raw: (frame) => { + const body = raw.get(frame) + return body === undefined ? undefined : ProviderShared.decodeJson(body) + }, + } + }), +} + // ============================================================================= // Protocol And Route // ============================================================================= @@ -600,16 +872,22 @@ export const protocol = Protocol.make({ sanitizer: "gemini", body: { schema: Body, from: fromRequest }, stream: { - event: Protocol.jsonEvent(Event), + event: Schema.Union([Schema.instanceOf(NextRequest), Schema.toType(Event), WireEvent]), initial: (request): ParserState => ({ route: `${request.model.provider}/${request.model.route.id}`, metadataKey: request.model.route.providerMetadataKey ?? request.model.provider, lifecycle: Lifecycle.initial(), + hop: 0, + hasToolCalls: false, + continuedUsage: [], steps: {}, tools: ToolStream.empty(), }), step, - terminal: (event) => event.event_type === "interaction.completed", + terminal: (event) => + !(event instanceof NextRequest) && + event.event_type === "interaction.completed" && + event.interaction.status !== CONTINUATION, }, }) @@ -620,7 +898,7 @@ export const route = Route.make({ protocol, endpoint: Endpoint.path("/interactions", { baseURL: DEFAULT_BASE_URL }), auth: Auth.none, - framing: Framing.sse, + transport, }) export * as GoogleInteractions from "./google-interactions.js" diff --git a/packages/ai/src/protocols/utils/gemini-generate-content.ts b/packages/ai/src/protocols/utils/gemini-generate-content.ts index 902826b3808b..853f5b2decf6 100644 --- a/packages/ai/src/protocols/utils/gemini-generate-content.ts +++ b/packages/ai/src/protocols/utils/gemini-generate-content.ts @@ -11,11 +11,30 @@ import { type MediaUsage, type ProviderMetadata, } from "../../schema/index.js" -import { ProviderShared } from "../shared.js" +import { knownString, ProviderShared } from "../shared.js" import { MediaInput } from "./media-input.js" const PROVIDER = ProviderID.make("google") +export const SafetySetting = Schema.Struct({ + category: knownString< + | "HARM_CATEGORY_UNSPECIFIED" + | "HARM_CATEGORY_HATE_SPEECH" + | "HARM_CATEGORY_DANGEROUS_CONTENT" + | "HARM_CATEGORY_HARASSMENT" + | "HARM_CATEGORY_SEXUALLY_EXPLICIT" + | "HARM_CATEGORY_CIVIC_INTEGRITY" + >(), + threshold: knownString< + | "HARM_BLOCK_THRESHOLD_UNSPECIFIED" + | "BLOCK_LOW_AND_ABOVE" + | "BLOCK_MEDIUM_AND_ABOVE" + | "BLOCK_ONLY_HIGH" + | "BLOCK_NONE" + | "OFF" + >(), +}) + const UsageMetadata = Schema.Struct({ promptTokenCount: Schema.optional(Schema.Number), candidatesTokenCount: Schema.optional(Schema.Number), diff --git a/packages/ai/src/provider-error.ts b/packages/ai/src/provider-error.ts index 162ee259f4e2..e2d5b7776fba 100644 --- a/packages/ai/src/provider-error.ts +++ b/packages/ai/src/provider-error.ts @@ -130,6 +130,8 @@ const CONTENT_POLICY_CODES = new Set([ "responsibleaipolicyviolation", "content_policy_violation", "image_content_policy_violation", + // OpenAI's cybersecurity safeguard, as an HTTP 400 or a mid-stream error frame. + "cyber_policy", "refusal", "datainspectionfailed", "moderation_blocked", @@ -156,7 +158,7 @@ const QUOTA_TEXT = // Bedrock Mantle reuses it for schema validation; Anthropic reports blocked output // under `invalid_request_error`. The Vercel AI Gateway drops OpenAI's `moderation_blocked` code. const CONTENT_POLICY_TEXT = - /violating our usage policy|blocked by content filtering policy|content[-_\s]?policy|rejected (?:as a result of our|by the) safety system|detected potentially unsafe or sensitive content/i + /violating our usage policy|blocked by content filtering policy|content[-_\s]?policy|rejected (?:as a result of our|by the) safety system|detected potentially unsafe or sensitive content|rejected in accordance with our terms of use/i const SERVER_ERROR_TEXT = /\b(?:try again|(?:please |you can )?retry (?:the |this |your )?request|try (?:the |this |your )?request again|(?:currently |temporarily )?at capacity|overloaded|temporarily unavailable|service[-_\s]?unavailable|(?:server|internal)[-_\s]?error|server (?:is )?busy|provider returned (?:an )?error|resource[-_\s]?exhausted|upstream (?:connect|connection|request)|request buffer limit while retrying upstream)\b/i diff --git a/packages/ai/src/providers/google-vertex-interactions.ts b/packages/ai/src/providers/google-vertex-interactions.ts index f3aa1e681a63..bb33036c00a8 100644 --- a/packages/ai/src/providers/google-vertex-interactions.ts +++ b/packages/ai/src/providers/google-vertex-interactions.ts @@ -3,7 +3,6 @@ import { GoogleInteractions } from "../protocols/google-interactions.js" import { Auth } from "../route/auth.js" import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { Framing } from "../route/framing.js" import { ProviderConfigurationError, ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" @@ -41,7 +40,7 @@ const route = Route.make({ const serviceTier = request.providerOptions?.serviceTier return typeof serviceTier === "string" ? { "x-vertex-ai-llm-shared-request-type": serviceTier } : {} }, - framing: Framing.sse, + transport: GoogleInteractions.transport, }) export const routes = [route] diff --git a/packages/ai/test/provider-error.test.ts b/packages/ai/test/provider-error.test.ts index 2da501ed6f85..a0e1633a3678 100644 --- a/packages/ai/test/provider-error.test.ts +++ b/packages/ai/test/provider-error.test.ts @@ -205,6 +205,20 @@ describe("provider error classification", () => { ).toEqual(["ContentPolicy", "ContentPolicy", "ContentPolicy"]) }) + test("classifies OpenAI cyber policy refusals before and during a stream", () => { + const message = + "This content was flagged for possible cybersecurity risk. If this seems wrong, try rephrasing your request." + const http = { error: { message, type: "invalid_request_error", param: null, code: "cyber_policy" } } + const frame = { type: "error", sequence_number: 1, code: "cyber_policy", message, param: null } + + expect( + [ + classifyProviderFailure({ message, status: 400, rawBody: JSON.stringify(http) }), + classifyProviderFailure({ message: `cyber_policy: ${message}`, rawBody: JSON.stringify(frame) }), + ].map((failure) => failure._tag), + ).toEqual(["ContentPolicy", "ContentPolicy"]) + }) + test("classifies Alibaba Model Studio data inspection failures", () => { const alibaba = { request_id: "1537ecc9-6873-93f7-9865-6fe4eb1d7851", @@ -261,6 +275,19 @@ describe("provider error classification", () => { ).toBe("ContentPolicy") }) + test("classifies Gemini terms-of-use refusals as policy rejections, not authentication failures", () => { + const message = "Request rejected in accordance with our terms of use and policies." + const gemini = { error: { code: 403, message, status: "PERMISSION_DENIED" } } + const zen = { error: { type: "server_error", message: `Upstream request failed: [403] ${message}` } } + + expect( + [gemini, zen].map( + (body) => + classifyProviderFailure({ message: body.error.message, status: 403, rawBody: JSON.stringify(body) })._tag, + ), + ).toEqual(["ContentPolicy", "ContentPolicy"]) + }) + test("keeps invalid_prompt schema validation failures as invalid requests", () => { // Bedrock Mantle reports request validation failures under `invalid_prompt` // with a pydantic dump that lists every input union member's fields. diff --git a/packages/ai/test/provider/google-interactions.test.ts b/packages/ai/test/provider/google-interactions.test.ts index d75171b2c24a..0015e0661ad2 100644 --- a/packages/ai/test/provider/google-interactions.test.ts +++ b/packages/ai/test/provider/google-interactions.test.ts @@ -1,10 +1,11 @@ import { describe, expect } from "bun:test" -import { Effect } from "effect" -import { ai, isRetryable } from "../../src/effect.js" +import { Deferred, Effect, Fiber, Stream } from "effect" +import { ai, isRetryable, Media, Message } from "../../src/effect.js" import { Google } from "../../src/providers.js" import { LLMClient } from "../../src/route.js" +import { compileRequest } from "../../src/testing.js" import { it } from "../lib/effect.js" -import { fixedResponse } from "../lib/http.js" +import { dynamicResponse, fixedResponse } from "../lib/http.js" import { sseEvents } from "../lib/sse.js" const model = Google.configure({ apiKey: "test", baseURL: "https://generativelanguage.test/v1beta" }).interactions( @@ -15,6 +16,60 @@ const generate = (...events: ReadonlyArray) => LLMClient.generate(ai.request({ model, prompt: "Hi" })).pipe(Effect.provide(fixedResponse(sseEvents(...events)))) describe("Google Interactions", () => { + it.effect("sends Gemini safety settings in the Interactions request", () => + Effect.gen(function* () { + const bodies: unknown[] = [] + const layer = dynamicResponse((input) => + Effect.sync(() => { + bodies.push(JSON.parse(input.text)) + return input.respond( + sseEvents({ event_type: "interaction.completed", interaction: { status: "completed" } }), + { + headers: { "content-type": "text/event-stream" }, + }, + ) + }), + ) + const configured = Google.configure({ + apiKey: "test", + baseURL: "https://generativelanguage.test/v1beta", + providerOptions: { + safetySettings: [ + { category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_LOW_AND_ABOVE" }, + { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_ONLY_HIGH" }, + ], + }, + }).interactions("gemini-3.8-flash") + yield* LLMClient.generate(ai.request({ model: configured, prompt: "Hi" })).pipe(Effect.provide(layer)) + + expect(bodies).toHaveLength(1) + expect(bodies[0]).toHaveProperty("safety_settings", [ + { type: "harassment", threshold: "block_low_and_above" }, + { type: "hate_speech", threshold: "block_only_high" }, + ]) + expect(bodies[0]).not.toHaveProperty("safetySettings") + }), + ) + + it.effect("lowers DOCX as a document and rejects an undocumented Office MIME type", () => + Effect.gen(function* () { + const docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + const docm = "application/vnd.ms-word.document.macroenabled.12" + const request = (mime: string) => ai.request({ model, prompt: Message.media(Media.base64("UEsDBA==", mime)) }) + + const compiled = yield* compileRequest(request(docx)) + expect(compiled.body.input).toEqual([ + { type: "user_input", content: [{ type: "document", mime_type: docx, data: "UEsDBA==" }] }, + ]) + + const error = yield* compileRequest(request(docm)).pipe(Effect.flip) + expect(error.reason).toMatchObject({ + _tag: "InvalidRequest", + message: `Google Interactions does not support ${docm} document input`, + }) + }), + ) + it.effect("classifies premature EOF before interaction.completed as an incomplete stream", () => Effect.gen(function* () { const error = yield* generate( @@ -127,8 +182,7 @@ describe("Google Interactions", () => { message: `Stream rejected: ${code}`, body: JSON.stringify(streamEvent), }) - if (fromError.reason._tag === "InvalidProviderOutput") - expect(fromError.reason.classification).toBeUndefined() + if (fromError.reason._tag === "InvalidProviderOutput") expect(fromError.reason.classification).toBeUndefined() expect(isRetryable(fromError)).toBe(false) } }), @@ -196,3 +250,344 @@ describe("Google Interactions", () => { }), ) }) + +describe("Google Interactions response continuation", () => { + const request = ai.request({ + model, + prompt: "Count.", + maxTokens: 66000, + tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object" } }], + }) + const scripted = (...responses: ReadonlyArray | Response>) => { + const bodies: Array> = [] + const layer = dynamicResponse((input) => + Effect.sync(() => { + const response = responses[Math.min(bodies.length, responses.length - 1)] + bodies.push(JSON.parse(input.text)) + if (response instanceof Response) return input.respond(response.body, response) + return input.respond(response, { headers: { "content-type": "text/event-stream" } }) + }), + ) + return { bodies, layer } + } + const startText = (index: number) => ({ event_type: "step.start", index, step: { type: "model_output" } }) + const text = (index: number, value: string) => ({ + event_type: "step.delta", + index, + delta: { type: "text", text: value }, + }) + const checkpoint = (token: string, usage?: Record) => ({ + event_type: "interaction.status_update", + status: "in_progress", + continuation_token: token, + usage, + }) + const completed = (interaction: Record = {}) => ({ + event_type: "interaction.completed", + interaction: { status: "completed", ...interaction }, + }) + + const continueWith = (token: string) => + sseEvents(completed({ status: "requires_continuation", continuation_token: token })) + + const disconnect = (frames: string, message: string) => { + let sent = false + return new ReadableStream({ + pull(controller) { + if (sent) return controller.error(new Error(message)) + sent = true + controller.enqueue(new TextEncoder().encode(frames)) + }, + }) + } + + it.effect("joins two hops into one response with signatures, tool calls, and combined usage", () => + Effect.gen(function* () { + const server = scripted( + sseEvents( + { + event_type: "step.start", + index: 0, + step: { type: "thought", summary: [{ type: "text", text: "Plan." }], signature: "signed-thought" }, + }, + { event_type: "step.stop", index: 0 }, + startText(1), + text(1, "One"), + checkpoint("older-checkpoint", { total_input_tokens: 7, total_output_tokens: 1 }), + text(1, ", two"), + completed({ + status: "requires_continuation", + continuation_token: "next-hop", + usage: { + total_input_tokens: 10, + total_cached_tokens: 3, + total_output_tokens: 3, + total_thought_tokens: 4, + total_tokens: 17, + }, + }), + ), + sseEvents( + startText(1), + text(1, ", three."), + { event_type: "step.stop", index: 1 }, + { + event_type: "step.start", + index: 2, + step: { type: "function_call", id: "call_1", name: "lookup", arguments: { count: 3 } }, + }, + { + event_type: "step.delta", + index: 2, + delta: { type: "thought_signature", signature: "signed-tool" }, + }, + { event_type: "step.stop", index: 2 }, + completed({ + id: "final-hop", + usage: { + total_input_tokens: 17, + total_cached_tokens: 10, + total_output_tokens: 4, + total_thought_tokens: 2, + total_tokens: 23, + }, + }), + ), + ) + const result = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer)) + + expect(server.bodies).toHaveLength(2) + expect(server.bodies[0]).toMatchObject({ store: false, generation_config: { max_output_tokens: 66000 } }) + expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuation_token: "next-hop" }) + expect(result.text).toBe("One, two, three.") + expect(result.reasoning).toBe("Plan.") + expect(result.events.find((event) => event.type === "reasoning-end")).toMatchObject({ + providerMetadata: { google: { interactionSignature: "signed-thought" } }, + }) + expect(result.toolCalls).toMatchObject([ + { + id: "call_1", + input: { count: 3 }, + providerMetadata: { google: { interactionSignature: "signed-tool" } }, + }, + ]) + expect(result.events.filter((event) => event.type === "finish")).toHaveLength(1) + expect(result.events.filter((event) => event.type === "step-start")).toHaveLength(1) + expect(result.finishReason).toEqual({ normalized: "tool-calls", raw: "completed" }) + expect(result.events.find((event) => event.type === "finish")).toMatchObject({ + providerMetadata: { google: { interactionId: "final-hop" } }, + }) + expect(result.usage).toMatchObject({ + inputTokens: 10, + nonCachedInputTokens: 7, + cacheReadInputTokens: 3, + outputTokens: 13, + reasoningTokens: 6, + totalTokens: 23, + providerMetadata: { + google: { + total_input_tokens: 27, + total_cached_tokens: 13, + total_output_tokens: 7, + total_thought_tokens: 6, + total_tokens: 40, + requests: 2, + }, + }, + }) + }), + ) + + it.effect("resumes a broken connection at a checkpoint with no later output", () => + Effect.gen(function* () { + const frames = sseEvents( + startText(0), + text(0, "One"), + checkpoint("resume", { total_input_tokens: 10, total_output_tokens: 1 }), + { event_type: "step.stop", index: 0 }, + ) + const server = scripted( + disconnect(frames, "connection reset"), + sseEvents( + startText(0), + text(0, ", two."), + completed({ usage: { total_input_tokens: 11, total_output_tokens: 2 } }), + ), + ) + const result = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer)) + + expect(server.bodies).toHaveLength(2) + expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuation_token: "resume" }) + expect(result.text).toBe("One, two.") + expect(result.usage).toMatchObject({ inputTokens: 10, outputTokens: 3 }) + }), + ) + + it.effect("does not replay visible output emitted after a checkpoint", () => + Effect.gen(function* () { + const server = scripted( + sseEvents(startText(0), text(0, "One"), checkpoint("stale"), text(0, ", two"), checkpoint("stale")), + ) + const error = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer), Effect.flip) + + expect(server.bodies).toHaveLength(1) + expect(error.partial?.text).toBe("One, two") + expect(error.reason).toMatchObject({ _tag: "InvalidProviderOutput", classification: "incomplete-stream" }) + expect(isRetryable(error)).toBe(true) + }), + ) + + it.effect("does not resume a tool call whose arguments or completion can be replayed", () => + Effect.gen(function* () { + const server = scripted( + sseEvents( + { + event_type: "step.start", + index: 0, + step: { type: "function_call", id: "call_1", name: "lookup", arguments: {} }, + }, + checkpoint("stale"), + { event_type: "step.delta", index: 0, delta: { type: "arguments_delta", arguments: "{}" } }, + ), + ) + const error = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer), Effect.flip) + + expect(server.bodies).toHaveLength(1) + expect(error.reason).toMatchObject({ _tag: "InvalidProviderOutput", classification: "incomplete-stream" }) + }), + ) + + it.effect("continues from a status update owned by a stored interaction", () => + Effect.gen(function* () { + const server = scripted( + sseEvents( + { ...checkpoint("stored-token"), interaction_id: "hop-owner", status: "requires_continuation" }, + completed({ status: "requires_continuation" }), + ), + sseEvents(completed()), + ) + yield* LLMClient.generate({ ...request, providerOptions: { store: true } }).pipe(Effect.provide(server.layer)) + + expect(server.bodies).toHaveLength(2) + expect(server.bodies[1]).not.toHaveProperty("input") + expect(server.bodies[1]).toMatchObject({ + store: true, + continuation_token: "stored-token", + previous_interaction_id: "hop-owner", + }) + }), + ) + + it.effect("cancels a continued response without reconnecting from its checkpoint", () => + Effect.gen(function* () { + const checkpointRead = yield* Deferred.make() + const server = scripted( + sseEvents(completed({ status: "requires_continuation", continuation_token: "next-hop" })), + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(sseEvents(checkpoint("resume")))) + }, + }), + ) + const fiber = yield* LLMClient.stream({ ...request, includeRaw: true }).pipe( + Stream.tap((event) => + event.type === "raw" && JSON.stringify(event.data).includes('"continuation_token":"resume"') + ? Deferred.succeed(checkpointRead, undefined) + : Effect.void, + ), + Stream.runDrain, + Effect.provide(server.layer), + Effect.forkChild({ startImmediately: true }), + ) + yield* Deferred.await(checkpointRead) + yield* Fiber.interrupt(fiber) + + expect(server.bodies).toHaveLength(2) + }), + ) + + it.effect("stops when a completed hop returns its own start token", () => + Effect.gen(function* () { + const server = scripted(continueWith("repeat"), continueWith("repeat"), sseEvents(completed())) + const error = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer), Effect.flip) + + expect(server.bodies.map((body) => body.continuation_token)).toEqual([undefined, "repeat"]) + expect(error.reason).toMatchObject({ _tag: "InvalidProviderOutput", classification: "incomplete-stream" }) + }), + ) + + it.effect("reconnects three times without progress and surfaces the last disconnect", () => + Effect.gen(function* () { + const empty = sseEvents() + const server = scripted( + continueWith("repeat"), + disconnect(empty, "first connection reset"), + empty, + disconnect(empty, "last connection reset"), + empty, + sseEvents(completed()), + ) + const error = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer), Effect.flip) + + expect(server.bodies.map((body) => body.continuation_token)).toEqual([ + undefined, + "repeat", + "repeat", + "repeat", + "repeat", + ]) + expect(error.reason).toMatchObject({ + _tag: "InvalidProviderOutput", + classification: "incomplete-stream", + message: expect.stringContaining("last connection reset"), + }) + expect(isRetryable(error)).toBe(true) + }), + ) + + it.effect("resets the reconnect budget after a new checkpoint", () => + Effect.gen(function* () { + const empty = sseEvents() + const server = scripted( + continueWith("first"), + empty, + empty, + empty, + sseEvents(checkpoint("new")), + empty, + empty, + empty, + sseEvents(completed()), + ) + const result = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer)) + + expect(server.bodies.map((body) => body.continuation_token)).toEqual([ + undefined, + "first", + "first", + "first", + "first", + "new", + "new", + "new", + "new", + ]) + expect(result.finishReason.normalized).toBe("stop") + }), + ) + + it.effect("does not resume when a continuation request gets an HTTP error", () => + Effect.gen(function* () { + const server = scripted( + continueWith("next-hop"), + Response.json({ error: { message: "Too many requests" } }, { status: 429 }), + sseEvents(completed()), + ) + const error = yield* LLMClient.generate(request).pipe(Effect.provide(server.layer), Effect.flip) + + expect(server.bodies.map((body) => body.continuation_token)).toEqual([undefined, "next-hop"]) + expect(error.reason).toMatchObject({ _tag: "RateLimit", http: { status: 429 } }) + expect(isRetryable(error)).toBe(true) + }), + ) +}) diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md index 412d1898e9c2..9afd09bcb2f1 100644 --- a/packages/app/AGENTS.md +++ b/packages/app/AGENTS.md @@ -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 `` 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`. diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts index ff9546fb3827..a05fbae9784e 100644 --- a/packages/app/component-tests/browser-pane-restore.spec.ts +++ b/packages/app/component-tests/browser-pane-restore.spec.ts @@ -1,3 +1,4 @@ +import type { Locator, Page } from "@playwright/test" import { expect, sourceURL, story } from "../../stories/playwright/story" import type { Accessor, ParentProps } from "solid-js" import type { Command, MenuItem } from "@opencode/plugin/gui" @@ -214,6 +215,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 +262,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 +338,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 }) => { @@ -663,13 +693,13 @@ story("selects side tabs with ⌘1–9 and ⇧⌘[ ] inside the side panel and s await expect(selected).toHaveText(/^browser:/) }) -story("keeps a restored browser tab selected and undrawn until the desktop's first inventory", async ({ page }) => { +story("keeps a restored browser tab with no saved page selected and undrawn until the desktop's first inventory", async ({ page }) => { const root = page.getByTestId("browser-region-fixture") const tabs = root.getByRole("tab") await expect(root.getByText("Registrations: 1", { exact: true })).toBeVisible() await expect(tabs).toHaveText(["alpha.ts"]) - // Beta was left on its browser tab, which the desktop has not reported yet. + // Beta was left on its browser tab, which the desktop has not reported yet and no earlier run saved a title for. await root.getByRole("button", { name: "Beta", exact: true }).click() await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible() await expect(root.getByTestId("selected")).toHaveText(/^browser:tab_/) @@ -680,6 +710,229 @@ 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") }) +// What main sends for Beta's two tabs, as production builds it: the inventory `pane-machine.ts` publishes and the page +// details `chromium.ts` reports. `electron-restore.test.ts` reads the titles a restored page publishes in real Electron. +type MainTab = { + id: string + url: string + title: string + loading: boolean + canGoBack: boolean + canGoForward: boolean + generation: number +} + +// The fixture reads each one through the pane Ipc's own event schema, so a shape main cannot send fails there. +type MainEvent = + | { type: "state"; state: { tabs: MainTab[]; focusedTabID: string } | null; error?: string } + | { type: "page"; tabID: string; zoom: number; viewport: { mode: "auto" }; icon?: string } + | { type: "embed"; tabID: string; embed: string } + +const preview = "tab_33333333-3333-3333-3333-333333333333" + +const docs = "tab_66666666-6666-6666-6666-666666666666" + +// A page's icon, as the data URL main reports. +const icon = (fill: string) => + `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' fill='${fill}'/%3E%3C/svg%3E` + +const previewIcon = icon("teal") + +const docsIcon = icon("orange") + +const reported = (tab: Pick & Partial): MainTab => ({ + loading: false, + canGoBack: false, + canGoForward: false, + generation: 0, + ...tab, +}) + +const inventory = (...tabs: MainTab[]): MainEvent => ({ type: "state", state: { tabs, focusedTabID: preview } }) + +const details = (tabID: string, icon?: string): MainEvent => + icon + ? { type: "page", tabID, zoom: 1, viewport: { mode: "auto" }, icon } + : { type: "page", tabID, zoom: 1, viewport: { mode: "auto" } } + +// The tabs as main restores them: saved by id and address, their pages not loaded, so neither reports a title. +const restoredPreview = reported({ id: preview, url: "http://localhost:4173/", title: "", generation: 1 }) + +const restoredDocs = reported({ id: docs, url: "https://example.com/docs", title: "", generation: 1 }) + +const send = async (root: Locator, event: MainEvent) => { + await root.getByRole("textbox", { name: "Main event", exact: true }).fill(JSON.stringify(event)) + await root.getByRole("button", { name: "Send main event", exact: true }).dispatchEvent("click") +} + +// Each strip tab's box, label and icon, as drawn now. +const drawn = (tabs: Locator) => + tabs.evaluateAll((nodes) => + nodes.map((node) => { + const box = node.getBoundingClientRect() + + return { x: box.x, width: box.width, text: node.textContent, icon: node.querySelector("img")?.getAttribute("src") ?? "none" } + }), + ) + +// Beta with two loaded browser tabs beside its file tab, then the app quits and opens again. +const reopen = async (page: Page, quit: () => Promise = async () => {}) => { + const root = page.getByTestId("browser-region-fixture") + const tabs = root.getByRole("tab") + await root.getByRole("button", { name: "Beta", exact: true }).click() + await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible() + await send(root, inventory(reported({ id: preview, url: "http://localhost:4173/", title: "Preview" }), reported({ id: docs, url: "https://example.com/docs", title: "Docs" }))) + await send(root, details(preview, previewIcon)) + await send(root, details(docs, docsIcon)) + await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs"]) + await quit() + await root.getByRole("button", { name: "Quit and reopen", exact: true }).dispatchEvent("click") + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs"]) + await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true") + await expect(root.getByRole("status", { name: "Loading", exact: true })).toBeVisible() + const first = await drawn(tabs) + const nodes = await tabs.elementHandles() + + // The same boxes, labels and icons as the first frame after the reopen, in the same elements: nothing moved. + const stable = async () => { + expect(await drawn(tabs)).toEqual(first) + expect( + await page.evaluate( + ([before, after]) => before.length === after.length && before.every((node, index) => node === after[index]), + [nodes, await tabs.elementHandles()], + ), + ).toBe(true) + } + + return { root, first, stable } +} + +// After a restart the strip showed no browser tab until the desktop had attached, and then each tab changed its label, +// and so its width and the place of every tab after it, as its page loaded: saved title, address, title again. +story("holds every restored tab's box, label and icon from the reopen until its page has loaded", async ({ page }) => { + // The pane's Ipc is still starting when the window draws its first frame. + const { root, first, stable } = await reopen(page, () => page.getByTestId("browser-region-fixture").getByRole("button", { name: "Pane away", exact: true }).click()) + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible() + + await root.getByRole("button", { name: "Pane back", exact: true }).click() + await expect(root.getByText("Registrations: 3", { exact: true })).toBeVisible() + await stable() + + // Main attached and restored both tabs. Docs is never selected, so its page never loads and it never reports a title. + await send(root, inventory(restoredPreview, restoredDocs)) + await expect(address).toHaveValue("http://localhost:4173/") + await expect(root.getByRole("status", { name: "Loading", exact: true })).toHaveCount(0) + await stable() + + // The pane shows Preview, so main creates its page, which starts to load. + await send(root, { type: "embed", tabID: preview, embed: "embed-preview" }) + await send(root, inventory({ ...restoredPreview, loading: true }, restoredDocs)) + await expect(root.getByRole("button", { name: "Stop", exact: true })).toBeVisible() + await stable() + + // The document commits where its address redirected to, with no title and no icon yet. + const committed = { ...restoredPreview, url: "http://localhost:4173/app", loading: true } + await send(root, inventory(committed, restoredDocs)) + await send(root, details(preview)) + await expect(address).toHaveValue("http://localhost:4173/app") + await stable() + + // It names itself, its icon arrives, and it stops loading. + await send(root, inventory({ ...committed, title: "Preview" }, restoredDocs)) + await stable() + await send(root, details(preview, previewIcon)) + await stable() + await send(root, inventory({ ...committed, title: "Preview", loading: false }, restoredDocs)) + await expect(root.getByRole("button", { name: "Reload", exact: true })).toBeVisible() + await stable() + // What held all along is the saved icon of each page, not the globe. + expect(first.map((tab) => tab.icon)).toEqual([expect.any(String), previewIcon, docsIcon]) +}) + +// A server without a browser left its restored tabs on a loader with no end. +story("a restored tab on a server without a browser says that the browser could not open, and keeps its box", async ({ page }) => { + const { root, stable } = await reopen(page) + const failed = root.getByRole("alert").filter({ hasText: "The browser couldn't open" }) + const loading = root.getByRole("status", { name: "Loading", exact: true }) + await expect(root.getByText("Registrations: 3", { exact: true })).toBeVisible() + + // Main closes the binding: the session's server has no browser. + await send(root, { type: "state", state: null, error: "browser.pane.unsupported" }) + await expect(failed).toBeVisible() + await expect(loading).toHaveCount(0) + await stable() + + // Trying again registers once more and waits for it; the tabs stay where they are, and the browser opens. + await failed.getByRole("button", { name: "Try again", exact: true }).click() + await expect(root.getByText("Registrations: 4", { exact: true })).toBeVisible() + await expect(loading).toBeVisible() + await stable() + await send(root, inventory(restoredPreview, restoredDocs)) + await expect(root.getByRole("combobox", { name: "Browser address", exact: true })).toHaveValue("http://localhost:4173/") + await stable() +}) + +// 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 +956,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") + }, +) diff --git a/packages/app/component-tests/browser-pane.spec.ts b/packages/app/component-tests/browser-pane.spec.ts index 45541a7e8650..039cce3987ad 100644 --- a/packages/app/component-tests/browser-pane.spec.ts +++ b/packages/app/component-tests/browser-pane.spec.ts @@ -1,11 +1,12 @@ -import { expect, sourceURL, story } from "../../stories/playwright/story" import type { Locator, 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/panel.fixture.tsx"), embeds: source("../src/runtime/plugin/embeds.tsx"), + links: source("../src/runtime/plugin/app-links.ts"), panelMotion: source("../src/shell/panel-motion.ts"), language: source("../src/runtime/i18n/language.tsx"), } @@ -19,23 +20,408 @@ const pinPlatform = (page: Page, platform: string) => story.beforeEach(async ({ mount, page }) => { // Any story loads the app styles; the fixture mounts the pane beside it on the real host embeds. await mount("ui-line-comment--editor") + await mountPane(page) + await expect(page.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") +}) + +async function mountPane(page: Page) { await page.evaluate(async (modules) => { - const [{ mountBrowserPane }, { createEmbeds }, panelMotion, language] = await Promise.all([ + const [{ mountBrowserPane }, { createEmbeds }, { appLinkRoute, createAppLinks }, panelMotion, language] = await Promise.all([ import(modules.fixture), import(modules.embeds), + import(modules.links), import(modules.panelMotion), import(modules.language), ]) mountBrowserPane({ createEmbeds, + createAppLinks, + appLinkRoute, panelMotion, LanguageProvider: language.LanguageProvider, UiI18nBridge: language.UiI18nBridge, useLanguage: language.useLanguage, }) }, modules) - await expect(page.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") +} + +story("reviews the actual application target only after a trusted click", async ({ page }) => { + const sanitizer = sourceURL(new URL("../../session-ui/src/components/markdown-cache.tsx", import.meta.url)) + const url = "obsidian://open?vault=test&file=report" + await page.evaluate(async ({ sanitizer, url }) => { + const { enableMarkdownAppLinks, sanitizeMarkdown } = await import(sanitizer) + const row = document.createElement("div") + row.dataset.paneRow = "" + row.innerHTML = sanitizeMarkdown(`Misleading title`) + enableMarkdownAppLinks(row) + document.querySelector('[data-testid="browser-pane-fixture"]')?.prepend(row) + row.querySelector("a")?.click() + }, { sanitizer, url }) + const pane = page.locator("#browser-panel") + await expect(pane.getByText(url)).toHaveCount(0) + const link = page.getByRole("link", { name: "Misleading title" }) + await link.hover() + await page.mouse.down() + await link.evaluate((node) => node.replaceWith(node.cloneNode(true))) + await page.mouse.up() + await expect(pane.getByText(url)).toHaveCount(0) + await link.click({ button: "middle" }) + await link.click({ modifiers: ["Shift"] }) + await link.hover() + await page.mouse.down() + await link.evaluate(node => { node.dataset.appLink = "obsidian:changed" }) + await page.mouse.up() + await expect(pane.getByText("obsidian:changed")).toHaveCount(0) + await expect(pane.getByRole("button", { name: "Open", exact: true })).toHaveCount(0) + await link.evaluate((node, url) => { node.dataset.appLink = url }, url) + await link.press("Enter") + await expect(pane.getByRole("status").filter({ hasText: "From the conversation" })).toContainText(url) + await expect(pane.getByRole("button", { name: "Open", exact: true })).toBeVisible() + // A synthetic press on the guarded button cannot answer the review, even after a real Enter on the link. + await pane.getByRole("button", { name: "Open", exact: true }).evaluate((button: HTMLElement) => button.click()) + await expect(pane.getByText(url)).toBeVisible() + // A fresh notice reuses the bar but not the earlier notice's press or activation time. + await link.click() + const open = pane.getByRole("button", { name: "Open", exact: true }) + await open.click() + await expect(pane.getByText(url)).toBeVisible() + const longest = "obsidian://open?file=".padEnd(200, "W") + await pane.evaluate(node => { node.style.width = "320px" }) + await link.evaluate((node, value) => { node.dataset.appLink = value }, longest) + await link.press("Enter") + await expect(pane.getByText(longest)).toBeVisible() + await expect(open).toBeVisible() + // A font or width that doesn't fit five lines downgrades the same notice without changing its target. + await pane.evaluate(node => { node.style.width = "240px" }) + await expect(pane.getByRole("button", { name: "Copy link", exact: true })).toBeVisible() + await expect(open).toHaveCount(0) +}) + +story("accepts an assistive activation of the focused link, not a synthetic or unfocused one", async ({ page }) => { + const sanitizer = sourceURL(new URL("../../session-ui/src/components/markdown-cache.tsx", import.meta.url)) + // A phone link keeps its href, so Chromium activates it on Enter. + const url = "tel:+15555550100" + await page.evaluate(async ({ sanitizer, url }) => { + const { enableMarkdownAppLinks, sanitizeMarkdown } = await import(sanitizer) + const row = document.createElement("div") + row.dataset.paneRow = "" + row.innerHTML = sanitizeMarkdown(`Assistive link Other`) + enableMarkdownAppLinks(row) + document.querySelector('[data-testid="browser-pane-fixture"]')?.prepend(row) + // A screen reader's default action is a trusted click with no press. Chromium sends the same one for Enter on a + // live link when nothing handles the key, so keep the app's own Enter handling out of the way. + window.addEventListener( + "keydown", + (event) => { + if (event.key !== "Enter" || !document.body.dataset.assistive) return + event.stopImmediatePropagation() + + if (document.body.dataset.assistive === "unfocused") row.querySelectorAll("a")[1]?.focus() + }, + true, + ) + }, { sanitizer, url }) + const pane = page.locator("#browser-panel") + const link = page.getByRole("link", { name: "Assistive link" }) + await link.focus() + await link.evaluate((node) => node.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 }))) + await page.evaluate(() => { document.body.dataset.assistive = "unfocused" }) + await link.focus() + await page.keyboard.press("Enter") + await expect(page.getByRole("link", { name: "Other" })).toBeFocused() + await expect(pane.getByText(url)).toHaveCount(0) + await page.evaluate(() => { document.body.dataset.assistive = "focused" }) + await link.focus() + await page.keyboard.press("Enter") + await expect(pane.getByRole("status").filter({ hasText: "From the conversation" })).toContainText(url) +}) + +story("reviews an application link that carries download, and leaves a web download to the document", async ({ page }) => { + const sanitizer = sourceURL(new URL("../../session-ui/src/components/markdown-cache.tsx", import.meta.url)) + await page.evaluate(async (sanitizer) => { + const { enableMarkdownAppLinks, sanitizeMarkdown } = await import(sanitizer) + const row = document.createElement("div") + row.dataset.paneRow = "" + row.dataset.testid = "download-links" + row.innerHTML = sanitizeMarkdown( + 'Mail Vault Report', + ) + enableMarkdownAppLinks(row) + // A reviewed click never reaches here. Record the ones left to the document, and keep the fixture page in place. + row.addEventListener("click", (event) => { + row.dataset.passed = `${row.dataset.passed ?? ""}${event.target instanceof Element ? event.target.textContent : ""}` + event.preventDefault() + }) + document.querySelector('[data-testid="browser-pane-fixture"]')?.prepend(row) + }, sanitizer) + const notice = page.locator("#browser-panel").getByRole("status").filter({ hasText: "From the conversation" }) + const mail = page.getByRole("link", { name: "Mail" }) + await expect(mail).not.toHaveAttribute("download") + // The attribute put back after sanitizing does not take the link past the host either: a mail link with an + // attachment is only copied. + await mail.evaluate((node) => node.setAttribute("download", "")) + await mail.click() + await expect(page.locator("body")).toHaveAttribute("data-copy", "mailto:download@example.invalid?attach=fixture") + await expect(notice).toHaveCount(0) + await page.getByRole("link", { name: "Vault" }).click() + await expect(notice).toContainText("obsidian://open?vault=download") + await page.getByRole("link", { name: "Report" }).click() + await expect(page.getByTestId("download-links")).toHaveAttribute("data-passed", "Report") + await expect(notice).toContainText("obsidian://open?vault=download") +}) + +story("opens a mail link in the system mail app, never in the pane", async ({ page }) => { + const sanitizer = sourceURL(new URL("../../session-ui/src/components/markdown-cache.tsx", import.meta.url)) + const url = "mailto:hello@example.invalid?subject=Report" + await page.evaluate(async ({ sanitizer, url }) => { + const { enableMarkdownAppLinks, sanitizeMarkdown } = await import(sanitizer) + const row = document.createElement("div") + row.dataset.paneRow = "" + row.innerHTML = sanitizeMarkdown(`Write to us`) + enableMarkdownAppLinks(row) + // A click the host does not take would navigate the fixture page away. + row.addEventListener("click", (event) => event.preventDefault()) + document.querySelector('[data-testid="browser-pane-fixture"]')?.prepend(row) + }, { sanitizer, url }) + await page.getByRole("link", { name: "Write to us" }).click() + await expect(page.locator("body")).toHaveAttribute("data-mail", url) + await expect(page.locator("#browser-panel").getByText(url)).toHaveCount(0) + await expect(page.locator("#browser-panel").getByRole("status").filter({ hasText: "From the conversation" })).toHaveCount(0) +}) + +story("moves the native page when a fixed-size pane changes position", async ({ page }) => { + const native = page.getByTestId("native-Alpha") + const x = Number(await native.getAttribute("data-x")) + const calls = Number(await native.getAttribute("data-layout-calls")) + await page.locator("#browser-panel").evaluate((pane) => { + pane.style.translate = "-12px" + pane.style.translate = "-24px" + pane.style.translate = "-39px" + }) + await expect(native).toHaveAttribute("data-x", String(x - 39)) + await expect(native).toHaveAttribute("data-layout-calls", String(calls + 1)) +}) + +story("reconnects the observation spine after its panel reattaches", async ({ page }) => { + const native = page.getByTestId("native-Alpha") + const x = Number(await native.getAttribute("data-x")) + + const detached = await page.locator("#browser-panel").evaluateHandle((box) => { + const marker = document.createComment("panel slot") + box.replaceWith(marker) + const fragment = document.createDocumentFragment() + fragment.append(box) + + return { marker, fragment } + }) + + await expect(native).toHaveAttribute("data-visible", "false") + await detached.evaluate(({ marker, fragment }) => { marker.replaceWith(fragment) }) + await expect(native).toHaveAttribute("data-visible", "true") + await page.locator("#browser-panel").evaluate((box) => { box.parentElement!.style.translate = "-31px" }) + await expect(native).toHaveAttribute("data-x", String(x - 31)) +}) + +story("a spinner inside a persistent floating surface does not measure the pane each frame", async ({ page }) => { + const native = page.getByTestId("native-Alpha") + + const reads = await page.locator("#browser-panel").evaluate(async (panel) => { + const box = panel.querySelector('[data-component="browser-preview"] > :first-child')! + const rect = box.getBoundingClientRect.bind(box) + const count = { reads: 0 } + box.getBoundingClientRect = () => { + count.reads++ + + return rect() + } + + const surface = document.createElement("div") + surface.dataset.floatingOverlay = "" + const spinner = document.createElement("span") + const style = document.createElement("style") + style.textContent = "@keyframes fixture-spin { to { transform: rotate(1turn) } }" + spinner.style.cssText = "display:block; animation:fixture-spin 100ms linear infinite" + surface.append(style, spinner) + document.body.append(surface) + const cycle = () => new Promise(resolve => spinner.addEventListener("animationiteration", () => resolve(), { once: true })) + await cycle() + const initial = count.reads + await cycle() + const total = count.reads - initial + surface.remove() + + return total + }) + + expect(reads).toBe(0) + await expect(native).toHaveAttribute("data-visible", "true") +}) + +story("stops measuring the pane once a finite animation ends or is cancelled", async ({ page }) => { + const native = page.getByTestId("native-Alpha") + const x = Number(await native.getAttribute("data-x")) + + const reads = await page.locator("#browser-panel").evaluate(async (panel) => { + const box = panel.querySelector('[data-component="browser-preview"] > :first-child')! + const rect = box.getBoundingClientRect.bind(box) + const count = { reads: 0 } + box.getBoundingClientRect = () => { + count.reads++ + + return rect() + } + + const frames = (n: number) => + new Promise((resolve) => { + const step = (left: number) => (left ? requestAnimationFrame(() => step(left - 1)) : resolve()) + step(n) + }) + + const idle = async () => { + const before = count.reads + await frames(10) + + return count.reads - before + } + + const finished = panel.parentElement!.animate([{ translate: "0" }, { translate: "-20px" }], { duration: 120, fill: "forwards" }) + await finished.finished + await frames(2) + const afterFinish = await idle() + const cancelled = panel.parentElement!.animate([{ translate: "-20px" }, { translate: "-60px" }], { duration: 5_000 }) + await frames(3) + cancelled.cancel() + await frames(2) + const afterCancel = await idle() + + return { afterFinish, afterCancel, measured: count.reads > 0 } + }) + + expect(reads).toEqual({ afterFinish: 0, afterCancel: 0, measured: true }) + await expect(native).toHaveAttribute("data-x", String(x - 20)) +}) + +story("does not measure when the pane's own still enters or leaves its box", async ({ page }) => { + const reads = await page.locator("#browser-panel").evaluate(async (panel) => { + const box = panel.querySelector('[data-component="browser-preview"] > :first-child')! + const rect = box.getBoundingClientRect.bind(box) + const count = { reads: 0 } + box.getBoundingClientRect = () => { + count.reads++ + + return rect() + } + + const frames = () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) + const still = document.createElement("div") + still.className = "absolute inset-0 pointer-events-none" + box.prepend(still) + await frames() + still.remove() + await frames() + + return count.reads + }) + + expect(reads).toBe(0) +}) + +story("hides the page when a portalled surface grows over it by a text edit alone", async ({ page }) => { + const native = page.getByTestId("native-Alpha") + await page.emulateMedia({ reducedMotion: "reduce" }) + + const text = await page.locator("#browser-panel").evaluateHandle((panel) => { + const pane = panel.querySelector('[data-component="browser-preview"] > :first-child')!.getBoundingClientRect() + // A portal's wrapper keeps its size while the fixed surface inside it grows, as a toast region's does. + const wrapper = document.createElement("div") + const surface = document.createElement("div") + surface.dataset.floatingOverlay = "" + surface.style.cssText = `position:fixed; top:${pane.top + 8}px; left:${pane.left - 40}px; white-space:pre; font:16px monospace` + const text = document.createTextNode("x") + surface.append(text) + wrapper.append(surface) + document.body.append(wrapper) + + return text + }) + + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))) + await expect(native).toHaveAttribute("data-visible", "true") + await text.evaluate((node) => { node.data = "x".repeat(400) }) + await expect(native).toHaveAttribute("data-visible", "false") +}) + +story("covers the page with unmarked portalled surfaces but not tooltips or transparent wrappers", async ({ page }) => { + const native = page.getByTestId("native-Alpha") + + const portal = await page.locator("#browser-panel").evaluateHandle((panel) => { + const pane = panel.querySelector('[data-component="browser-preview"] > :first-child')!.getBoundingClientRect() + const box = `position:fixed; top:${pane.top + 8}px; left:${pane.left + 8}px; width:120px; height:60px` + const tooltip = document.createElement("div") + tooltip.innerHTML = `
Tip
` + const wrapper = document.createElement("div") + wrapper.style.cssText = "position:fixed; inset:0; pointer-events:none" + document.body.append(tooltip, wrapper) + const surface = document.createElement("div") + surface.innerHTML = `
Unmarked menu
` + + return { surface, wrapper } + }) + + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))) + await expect(native).toHaveAttribute("data-visible", "true") + await portal.evaluate(({ surface }) => document.body.append(surface)) + await expect(native).toHaveAttribute("data-visible", "false") + await portal.evaluate(({ surface, wrapper }) => wrapper.append(surface.firstElementChild!)) + await expect(native).toHaveAttribute("data-visible", "false") + await portal.evaluate(({ wrapper }) => wrapper.replaceChildren()) + await expect(native).toHaveAttribute("data-visible", "true") +}) + +story("covers the page with an app dialog's backdrop for as long as the backdrop is there", async ({ mount, page }) => { + // The fixture reports no open dialog to the embeds, and the dialog was portalled before the pane: only the marked + // backdrop itself covers the page, independent of the dialog stack's open state, which ends as the exit starts. + await mount("ui-dialog--with-popups") + await expect(page.getByRole("dialog", { name: "Popups" })).toBeVisible() + await mountPane(page) + const native = page.getByTestId("native-Alpha") + await expect(native).toHaveAttribute("data-layout-calls", /[1-9]/) + await expect(page.locator('[data-component="dialog-overlay"]')).toHaveCount(1) + await expect(native).toHaveAttribute("data-visible", "false") + await page.keyboard.press("Escape") + await expect(page.locator('[data-component="dialog-overlay"]')).toHaveCount(0) + await expect(native).toHaveAttribute("data-visible", "true") +}) + +story("tracks a fixed-size pane through a sibling resize, ancestor scroll and animation", async ({ page }) => { + const pane = page.locator("#browser-panel") + const native = page.getByTestId("native-Alpha") + const x = Number(await native.getAttribute("data-x")) + + const row = await pane.evaluateHandle((box) => { + const scroller = document.createElement("div") + const spacer = document.createElement("div") + const rect = box.getBoundingClientRect() + scroller.style.cssText = `display:flex; overflow:auto; width:${rect.width}px; height:${rect.height}px` + box.style.flex = `0 0 ${rect.width}px` + spacer.style.flex = "0 0 32px" + box.replaceWith(scroller) + scroller.append(spacer, box) + + return { spacer, scroller } + }) + + await expect(native).toHaveAttribute("data-x", String(x + 32)) + await row.evaluate(({ spacer }) => { spacer.style.flexBasis = "48px" }) + await expect(native).toHaveAttribute("data-x", String(x + 48)) + await row.evaluate(({ scroller }) => { scroller.scrollLeft = 19 }) + await expect(native).toHaveAttribute("data-x", String(x + 29)) + const motion = await row.evaluateHandle(({ scroller }) => scroller.animate([{ translate: "0" }, { translate: "-64px" }], { duration: 220, fill: "forwards" })) + await motion.evaluate(animation => animation.finished.then(() => undefined)) + await expect(native).toHaveAttribute("data-x", String(x - 35)) + await motion.evaluate(animation => animation.cancel()) + await expect(native).toHaveAttribute("data-x", String(x + 29)) }) story("hides a native page when another takes the pane, the pane hides, or it unmounts", async ({ page }) => { @@ -76,6 +462,21 @@ story("hides the native view immediately while the pane stays mounted", async ({ await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") }) +story("updates the selected match while the same find field stays focused", async ({ page }) => { + const pane = page.locator("#browser-panel") + await pane.getByRole("button", { name: "Browser options" }).click() + await page.getByRole("menuitem", { name: "Find in page" }).click() + const field = pane.getByRole("searchbox", { name: "Find in page" }) + await field.fill("landmark") + const count = pane.getByRole("search").getByRole("status") + await expect(count).toHaveText("1 of 3") + await field.press("Enter") + await expect(count).toHaveText("2 of 3") + await expect(field).toBeFocused() + await field.press("Escape") + await expect(field).toHaveCount(0) +}) + story("paints a still of the page in place of the native view while a panel moves", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") const motion = root.getByRole("button", { name: "Toggle panel motion", exact: true }) @@ -144,32 +545,58 @@ story("paints a still of the page in place of the native view while a resize han await expect(still).toHaveCount(0) }) -story("keeps the native view live while a resize handle is dragged on macOS", async ({ page }) => { - const root = page.getByTestId("browser-pane-fixture") - const handle = root.getByTestId("pane-resize-handle") - const still = root.locator("#browser-panel img") - await pinPlatform(page, "MacIntel") - - // macOS puts a native view's bounds and the DOM around it on the same frame, so the page keeps laying out through the - // drag instead of freezing behind a still. Read in the same task as each move, so a blink between frames cannot pass. - const visible = await handle.evaluate((element) => { - const read = () => document.querySelector('[data-testid="native-Alpha"]')?.getAttribute("data-visible") - const box = element.getBoundingClientRect() - const at = { bubbles: true, pointerId: 1, clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 } - element.dispatchEvent(new PointerEvent("pointerdown", { ...at, button: 0 })) - document.dispatchEvent(new PointerEvent("pointermove", { ...at, clientX: at.clientX - 40 })) - const dragging = read() - document.dispatchEvent(new PointerEvent("pointermove", { ...at, clientX: at.clientX - 80 })) - const moved = read() - document.dispatchEvent(new PointerEvent("pointerup", at)) +for (const platform of ["MacIntel", "Win32"]) { + story(`keeps the native view live through a press, a drag and the release of a resize handle on ${platform}`, async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const handle = root.getByTestId("pane-resize-handle") + const native = root.getByTestId("native-Alpha") + const still = root.locator("#browser-panel img") + await pinPlatform(page, platform) + const box = await handle.boundingBox() + + if (!box) throw new Error("Missing pane resize handle") + const at = { x: box.x + box.width / 2, y: box.y + box.height / 2 } + const width = Number(await native.getAttribute("data-width")) + const calls = (await native.getAttribute("data-layout-calls")) ?? "" + + // macOS and Windows put a native view's bounds and the DOM around it on the same frame, so the page keeps laying + // out through the drag instead of hiding behind a still, which blanks the box until the still paints. Every change + // of the view's visibility is recorded, so one hidden and shown again before the next frame cannot pass. + const flips = await native.evaluateHandle((element) => { + const flips: (string | null)[] = [] + new MutationObserver((records) => flips.push(...records.map((record) => record.oldValue))).observe(element, { + attributeFilter: ["data-visible"], + attributeOldValue: true, + }) + + return flips + }) - return { dragging, moved } + const frames = () => + page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))) + + // A real press: the handle takes the pointer, and main hears nothing until it moves. + await page.mouse.move(at.x, at.y) + await page.mouse.down() + await expect(handle).toHaveAttribute("data-dragging", "") + await frames() + await expect(native).toHaveAttribute("data-layout-calls", calls) + + // Main gets the bounds of every move. + for (const moved of [10, 20, 30, 40]) { + await page.mouse.move(at.x - moved, at.y) + await expect(native).toHaveAttribute("data-width", String(width - moved)) + } + + await expect(still).toHaveCount(0) + await page.mouse.up() + await expect(handle).not.toHaveAttribute("data-dragging") + await frames() + await expect(native).toHaveAttribute("data-width", String(width - 40)) + await expect(still).toHaveCount(0) + expect(await flips.jsonValue()).toEqual([]) }) - - expect(visible).toEqual({ dragging: "true", moved: "true" }) - await expect(handle).not.toHaveAttribute("data-dragging") - await expect(still).toHaveCount(0) -}) +} story("shows the native view again when the window loses focus mid-drag", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") @@ -276,6 +703,61 @@ story("keeps a still of the page under floating content that covers it", async ( await expect(root.getByText("Captures: 1", { exact: true })).toBeVisible() }) +story("covers the page with its warm still only once the capture is back, and through the thaw", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const still = root.locator("#browser-panel img") + const native = root.getByTestId("native-Alpha") + const popover = root.getByRole("button", { name: "Toggle popover", exact: true }) + // Without reduced motion the pane keeps a still of the page for flights, which can cover the page at once. + await expect(root.getByText(/^Captures: [1-9]/)).toBeVisible() + const captures = Number((await root.getByText(/^Captures: \d+$/).textContent())?.split(": ")[1]) + await root.getByRole("button", { name: "Hold capture", exact: true }).click() + await popover.click() + await expect(root.getByText(`Captures: ${captures + 1}`, { exact: true })).toBeVisible() + // Main captures only a visible view: hiding it while the capture is out returns no fresh still. + await expect(still).toHaveCount(1) + await expect(native).toHaveAttribute("data-visible", "true") + await root.getByRole("button", { name: "Release capture", exact: true }).click() + await expect(native).toHaveAttribute("data-visible", "false") + await popover.click() + await expect(native).toHaveAttribute("data-visible", "true") + + // A capture that returns nothing still leaves the warm still over the hidden page, and over the page while it + // paints again after the cover ends. + // The fixture's controls below the pane sit outside the viewport. + await root.getByRole("button", { name: "Fail capture", exact: true }).evaluate((element: HTMLElement) => element.click()) + await popover.click() + await expect(native).toHaveAttribute("data-visible", "false") + await expect(still).toHaveCount(1) + + const frames = await popover.evaluate(async (button) => { + const samples: [string | null, number][] = [] + + const read = (): [string | null, number] => [ + document.querySelector('[data-testid="native-Alpha"]')?.getAttribute("data-visible") ?? null, + document.querySelectorAll("#browser-panel img").length, + ] + + button.dispatchEvent(new MouseEvent("click", { bubbles: true })) + await new Promise((resolve) => { + const step = () => { + samples.push(read()) + + if (samples.length < 60 && (samples.at(-1)?.[1] ?? 0) > 0) return requestAnimationFrame(step) + resolve() + } + + requestAnimationFrame(step) + }) + + return samples + }) + + expect(frames.filter(([visible, stills]) => visible === "false" && stills === 0)).toEqual([]) + expect(frames.some(([visible, stills]) => visible === "true" && stills > 0)).toBe(true) + await expect(still).toHaveCount(0) +}) + story( "freezes on the latest capture when floating content closes and reopens before a capture lands", async ({ page }) => { @@ -355,21 +837,21 @@ story("hides the native page under a dialog even when its still never arrives", story("comments on a picked element over a still of the page", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("combobox", { name: "Picked element scenario" }).selectOption("zoomed") - const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) + const picker = commentTool(page, root) await picker.click() - await expect(picker).toHaveAttribute("aria-pressed", "true") + await expect(picker.picking).toBeAttached() await expect(root.getByText("Picker: on", { exact: true })).toBeVisible() await expect(root.getByText("Session getter reads: 0", { exact: true })).toBeVisible() await expect(root.getByRole("status")).toHaveText( - "Click an element in the page to comment on it. Press Escape to cancel.", + "Click part of the page to comment on it. Press Escape to cancel.", ) await root.getByRole("button", { name: "Pick element", exact: true }).click() - await expect(picker).toHaveAttribute("aria-pressed", "false") + await expect(picker.picking).toHaveCount(0) const editor = root.locator('[data-slot="browser-comment-editor"] textarea') await expect(editor).toBeFocused() await expect(editor).toHaveAttribute("placeholder", "Add an optional comment...") - await expect(editor).toHaveAccessibleName("Comment on this element") + await expect(editor).toHaveAccessibleName("Comment on this part of the page") await expect(root.getByText("Session getter reads: 0", { exact: true })).toBeVisible() await expect(root.locator('[data-slot="browser-comment-editor"]')).toContainText("button.primary") // The spotlight frames the picked element in surface pixels. @@ -380,7 +862,7 @@ story("comments on a picked element over a still of the page", async ({ page }) await expect(root.locator("#browser-panel img")).toBeVisible() await editor.fill("Make this the primary colour") - await root.getByRole("button", { name: "Add element comment", exact: true }).click() + await root.getByRole("button", { name: "Add comment", exact: true }).click() await expect(root.getByTestId("fixture-comments")).toHaveText("button.primary @e7: Make this the primary colour") await expect(root.locator('[data-component="browser-comment"]')).toHaveCount(0) await expect(root.getByText("Highlights: clear", { exact: true })).toBeVisible() @@ -404,11 +886,11 @@ story("comments on a picked element over a still of the page", async ({ page }) story("cancels the picker and a comment with Escape", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") - const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) + const picker = commentTool(page, root) await picker.click() - await expect(picker).toHaveAttribute("aria-pressed", "true") + await expect(picker.picking).toBeAttached() await page.keyboard.press("Escape") - await expect(picker).toHaveAttribute("aria-pressed", "false") + await expect(picker.picking).toHaveCount(0) await expect(root.getByText("Picker: off", { exact: true })).toBeVisible() await picker.click() @@ -423,10 +905,10 @@ story("cancels the picker and a comment with Escape", async ({ page }) => { story("leaves the picker off and Escape to the app when main never answers", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") - const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) + const picker = commentTool(page, root) await root.getByRole("button", { name: "Drop picker requests", exact: true }).click() await picker.click() - await expect(picker).toHaveAttribute("aria-pressed", "false") + await expect(picker.picking).toHaveCount(0) const address = root.getByRole("combobox", { name: "Browser address", exact: true }) await address.click() @@ -437,8 +919,7 @@ story("leaves the picker off and Escape to the app when main never answers", asy story("replaces an open page note with the comment for an element picked meanwhile", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") - await root.locator('[data-component="browser-address"]').hover() - await root.getByRole("button", { name: "Add page to session", exact: true }).click() + await addPage(page, root) await expect(root.locator('[data-slot="browser-comment-editor"] textarea')).toBeFocused() await root.getByRole("button", { name: "Pick element", exact: true }).click() @@ -448,13 +929,13 @@ story("replaces an open page note with the comment for an element picked meanwhi story("cleans up the originating session's picker and comment after a session switch", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") - const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) + const picker = commentTool(page, root) await picker.click() await expect(root.getByText("Picker Alpha: on", { exact: true })).toBeVisible() await root.getByRole("button", { name: "Beta", exact: true }).click() await expect(root.getByTestId("native-Beta")).toHaveAttribute("data-visible", "true") await expect(root.getByText("Picker Alpha: off", { exact: true })).toBeVisible() - await expect(picker).toHaveAttribute("aria-pressed", "false") + await expect(picker.picking).toHaveCount(0) await root.getByRole("button", { name: "Alpha", exact: true }).click() await picker.click() @@ -468,7 +949,7 @@ story("cleans up the originating session's picker and comment after a session sw story("ends the native picker and highlight when the pane unmounts", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") - const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) + const picker = commentTool(page, root) await picker.click() await expect(root.getByText("Picker: on", { exact: true })).toBeVisible() await root.getByRole("button", { name: "Unmount pane", exact: true }).click() @@ -486,7 +967,7 @@ story("ends the native picker and highlight when the pane unmounts", async ({ pa story("keeps a comment draft but drops its ref when the page navigates", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") - await root.getByRole("button", { name: "Select an element to comment on", exact: true }).click() + await commentTool(page, root).click() await root.getByRole("button", { name: "Pick element", exact: true }).click() const editor = root.locator('[data-slot="browser-comment-editor"] textarea') await editor.fill("Still misaligned after the reload") @@ -501,7 +982,7 @@ story("keeps a comment draft but drops its ref when the page navigates", async ( story("grows the compact comment upward without flipping and keeps its actions inside the page", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("combobox", { name: "Picked element scenario" }).selectOption("low") - await root.getByRole("button", { name: "Select an element to comment on", exact: true }).click() + await commentTool(page, root).click() await root.getByRole("button", { name: "Pick element", exact: true }).click() const editor = root.locator('[data-slot="browser-comment-editor"]') const field = editor.locator("textarea") @@ -532,13 +1013,13 @@ story("grows the compact comment upward without flipping and keeps its actions i return !!surface && !!box && box.y >= surface.y && box.y + box.height <= surface.y + surface.height }) .toBe(true) - const submit = editor.getByRole("button", { name: "Add element comment", exact: true }) + const submit = editor.getByRole("button", { name: "Add comment", exact: true }) await submit.scrollIntoViewIfNeeded() await expect(submit).toBeInViewport() // Near the surface's top, growth stops at the opening bottom rather than pushing the card down. await field.press("Escape") await root.getByRole("combobox", { name: "Picked element scenario" }).selectOption("default") - await root.getByRole("button", { name: "Select an element to comment on", exact: true }).click() + await commentTool(page, root).click() await root.getByRole("button", { name: "Pick element", exact: true }).click() await expect(field).toBeFocused() const nearTop = await editor.boundingBox() @@ -580,7 +1061,7 @@ story( async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") const scenario = root.getByRole("combobox", { name: "Picked element scenario" }) - const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) + const picker = commentTool(page, root) const editor = root.locator('[data-slot="browser-comment-editor"]') const overlay = root.locator('[data-component="browser-comment"]') await scenario.selectOption("long") @@ -604,7 +1085,7 @@ story( await scenario.selectOption("default") await picker.click() await root.getByRole("button", { name: "Pick element", exact: true }).click() - await editor.getByRole("button", { name: "Add element", exact: true }).click() + await editor.getByRole("button", { name: "Add to session", exact: true }).click() await expect(overlay).toHaveCount(0) await expect(comments).toHaveText(["button.primary @e7:", "button.primary @e7:"]) expect(JSON.parse(await root.getByTestId("fixture-comment-metadata").innerText())).toEqual( @@ -730,29 +1211,48 @@ story("explains why a typed address cannot open instead of searching for it", as story("shows a themed failure state for only the failed tab and allows retry", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("button", { name: "Failed page", exact: true }).click() - await expect(root.getByText("URL can't be reached", { exact: true })).toBeVisible() - await expect(root.getByText("Check the URL and your connection, then try again.", { exact: true })).toBeVisible() - await expect(root.getByText("Request failed", { exact: true })).toBeHidden() + // The page area alone explains a load that failed: what happened in plain words, what to do, and Chromium's code + // small under it. Nothing is raised above the page beside it. + const failure = root.locator('[data-component="browser-failure"]') + await expect(failure.getByRole("heading", { name: "This site can't be reached", exact: true })).toBeVisible() + await expect(failure.getByText("Check the address for typing mistakes. If it is right, the site may be down.", { exact: true })).toBeVisible() + await expect(failure.getByText("ERR_CONNECTION_REFUSED", { exact: true })).toBeVisible() + await expect(root.getByRole("alert")).toHaveCount(0) await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "false") await expect(root.getByRole("combobox", { name: "Browser address", exact: true })).toHaveValue( "https://alpha.example/", ) await root.getByRole("button", { name: "Beta", exact: true }).click() - await expect(root.getByText("URL can't be reached", { exact: true })).toBeHidden() + await expect(root.getByText("This site can't be reached", { exact: true })).toBeHidden() await expect(root.getByTestId("native-Beta")).toHaveAttribute("data-visible", "true") await root.getByRole("button", { name: "Alpha", exact: true }).click() - await expect(root.getByText("URL can't be reached", { exact: true })).toBeVisible() + await expect(root.getByText("This site can't be reached", { exact: true })).toBeVisible() + await failure.getByRole("button", { name: "Reload", exact: true }).click() + await expect(root.getByText("This site can't be reached", { exact: true })).toBeHidden() + await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") +}) + +story("a command that did not work says what was tried above the page and offers it again", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Fail next command", exact: true }).click() await root.getByRole("button", { name: "Reload", exact: true }).click() - await expect(root.getByText("URL can't be reached", { exact: true })).toBeHidden() + const notice = root.locator('[data-component="browser-failure-bar"]') + // Main's own message never reaches the person, and neither does the app's generic failure text. + await expect(notice.getByRole("alert")).toHaveText("Couldn't reload this page.") + await expect(root.getByText("Request failed", { exact: true })).toHaveCount(0) + await expect(root.getByText("did not finish starting")).toHaveCount(0) + // The page stays where it was; trying again sends the same command, which takes the notice away. await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") + await notice.getByRole("button", { name: "Try again", exact: true }).click() + await expect(notice).toHaveCount(0) }) story("returns a failed tab to the empty state when an empty URL is submitted", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("button", { name: "Failed page", exact: true }).click() - await expect(root.getByText("URL can't be reached", { exact: true })).toBeVisible() + await expect(root.getByText("This site can't be reached", { exact: true })).toBeVisible() await root.getByRole("button", { name: "Delay navigation", exact: true }).click() const address = root.getByRole("combobox", { name: "Browser address", exact: true }) @@ -763,7 +1263,7 @@ story("returns a failed tab to the empty state when an empty URL is submitted", await root.getByRole("button", { name: "Load current page", exact: true }).click() await expect(root.getByRole("button", { name: "Stop", exact: true })).toBeEnabled() await root.getByRole("button", { name: "Complete navigation", exact: true }).click() - await expect(root.getByText("URL can't be reached", { exact: true })).toBeHidden() + await expect(root.getByText("This site can't be reached", { exact: true })).toBeHidden() await expect(root.getByText("Open a page", { exact: true })).toBeVisible() await expect(root.getByRole("button", { name: "Reload", exact: true })).toBeDisabled() await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "false") @@ -864,30 +1364,212 @@ story("keeps the current page and restores its URL when an empty address is subm await expect(root.getByRole("button", { name: "Reload", exact: true })).toBeEnabled() }) -story("suggests visited pages and opens the first one that completes the typed address", async ({ page }) => { +story("lists the typed text with visited pages, and opens the first row: the page the typing completes, else the text", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("button", { name: "Seed history", exact: true }).click() const address = root.getByRole("combobox", { name: "Browser address", exact: true }) await address.click() await address.pressSequentially("localhost") const options = page.getByRole("listbox", { name: "Suggestions" }).getByRole("option") - await expect(options).toHaveCount(1) + // The page whose address begins with the text is first and chosen; the search for the text follows it. + await expect(options).toHaveCount(2) await expect(options.first()).toHaveAttribute("aria-selected", "true") - // Arrow keys that pick IME candidates leave the suggestions alone. + await expect(address).toHaveValue("localhost:5173/settings") + // Arrow keys that pick IME candidates leave the list alone. await address.dispatchEvent("keydown", { key: "ArrowDown", isComposing: true }) await expect(options.first()).toHaveAttribute("aria-selected", "true") await address.press("Enter") await expect(address).toHaveValue("http://localhost:5173/settings") - // A search query also opens the first match; stepping past the list leaves the typed text, which searches. + // Words that only match a page list it below the search for them, which is first and chosen; a step down opens it. await address.click() await address.pressSequentially("color format") - await expect(options).toHaveCount(1) + await expect(options).toHaveCount(2) await expect(options.first()).toHaveAttribute("aria-selected", "true") - await address.press("ArrowDown") - await expect(options.first()).toHaveAttribute("aria-selected", "false") + await expect(options.first()).toHaveText("color format-Google Search") await address.press("Enter") await expect(address).toHaveValue("https://www.google.com/search?q=color%20format") + await address.click() + await address.pressSequentially("color format") + await address.press("ArrowDown") + await expect(options.nth(1)).toHaveAttribute("aria-selected", "true") + await address.press("Enter") + await expect(address).toHaveValue("https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Colors/Color_format_converter") +}) + +story("finds imported pages by their words, completes the site a host begins, and forgets a page on Shift+Delete", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Seed imported history", exact: true }).click() + await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible() + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + const options = page.getByRole("listbox", { name: "Suggestions" }).getByRole("option") + const addresses = () => options.locator('[data-slot="browser-page-row-url"]') + + // Main answers after the field shows the text: under the search for it, the list fills with the best matches of 59 + // pages, the most visited first, and a word found only inside another ("prune") last. + await address.click() + await address.pressSequentially("rune") + await expect(addresses()).toHaveText([ + "Google Search", + "github.com/anomalyco/rune-desktop", + "github.com/anomalyco/rune-desktop/pulls", + "docs.rune.example/guide/getting-started", + "github.com/anomalyco/rune-desktop/issues/128", + "github.com/runelabs/rune-lang", + ]) + await expect(options.nth(1).locator("mark")).toHaveText(["rune", "Rune", "rune"]) + // The search row is the typed text itself, so it draws no match. + await expect(options.first().locator("mark")).toHaveCount(0) + await expect(options.first()).toHaveAttribute("aria-selected", "true") + // Imported pages have no icon of their own: the globe stands in, and none is fetched. + await expect(options.locator("img")).toHaveCount(0) + + // Both words, in either order, wherever each starts a part of the address. + await address.fill("") + await address.pressSequentially("desk anom") + await expect(addresses()).toHaveText([ + "Google Search", + "github.com/anomalyco/rune-desktop", + "github.com/anomalyco/rune-desktop/pulls", + "github.com/anomalyco/rune-desktop/issues/128", + ]) + + // Shift+Delete forgets the chosen page, in main's history too; on the typed text's row the key is the field's own. + await address.fill("") + await address.pressSequentially("rune") + await expect(options).toHaveCount(6) + await address.press("Shift+Delete") + await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible() + await address.press("ArrowDown") + await address.press("Shift+Delete") + // The row that takes its place is the chosen one, and the field shows its address. + await expect(addresses().nth(1)).toHaveText("github.com/anomalyco/rune-desktop/pulls") + await expect(options.nth(1)).toHaveAttribute("aria-selected", "true") + await expect(address).toHaveValue("https://github.com/anomalyco/rune-desktop/pulls") + await expect(root.getByText("Main history: 58", { exact: true })).toBeVisible() + + // Text that begins a host completes its site, which Enter opens. + await address.fill("") + await address.pressSequentially("gith") + await expect(addresses().first()).toHaveText("github.com/") + await expect(options.first()).toHaveAttribute("aria-selected", "true") + await address.press("Enter") + await expect(address).toHaveValue("https://github.com/") +}) + +story("keeps the first row chosen and moves through the list with Chrome's keys", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Seed imported history", exact: true }).click() + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + const list = page.getByRole("listbox", { name: "Suggestions" }) + const options = list.getByRole("option") + const addresses = options.locator('[data-slot="browser-page-row-url"]') + const selection = () => address.evaluate((input: HTMLInputElement) => input.value.slice(input.selectionStart ?? 0, input.selectionEnd ?? 0)) + // The places of the chosen rows: always exactly one while the list is open. + const chosen = () => options.evaluateAll((rows) => rows.flatMap((row, place) => (row.getAttribute("aria-selected") === "true" ? [place] : []))) + + // The typed text completes to the site: the rest of its address is in the field, selected, and its row is chosen. + await address.click() + await address.pressSequentially("gith") + await expect(address).toHaveValue("github.com") + await expect.poll(selection).toBe("ub.com") + await expect(addresses.first()).toHaveText("github.com/") + await expect(options.nth(1)).toHaveText("gith-Google Search") + await expect(options).toHaveCount(6) + await expect.poll(chosen).toEqual([0]) + + // Backspace removes the completed part only; deleting never completes, so the typed text is first and chosen. + await address.press("Backspace") + await expect(address).toHaveValue("gith") + await expect(options.first()).toHaveText("gith-Google Search") + await expect(addresses.nth(1)).toHaveText("github.com/") + await expect.poll(chosen).toEqual([0]) + // The next character completes again, and typing goes on through the selected part. + await address.pressSequentially("ub") + await expect(address).toHaveValue("github.com") + await expect.poll(selection).toBe(".com") + + // Down and Up choose a row and put its text in the field; past either end the choice goes around. + await address.press("ArrowDown") + await expect(address).toHaveValue("github") + await expect.poll(chosen).toEqual([1]) + await address.press("ArrowUp") + await expect(address).toHaveValue("https://github.com") + await address.press("ArrowUp") + await expect.poll(chosen).toEqual([5]) + await expect(address).toHaveValue(/^https:\/\/github\.com\/.+/) + // Tab moves as Down does while the list is open, and keeps the focus in the field. + await address.press("Tab") + await expect.poll(chosen).toEqual([0]) + await address.press("Tab") + await expect.poll(chosen).toEqual([1]) + await expect(address).toBeFocused() + + // Escape undoes one thing at a time: the row's text, the list, the typed text, then the focus. + await address.press("Escape") + await expect(address).toHaveValue("github.com") + await expect.poll(selection).toBe(".com") + await expect.poll(chosen).toEqual([0]) + await address.press("Escape") + await expect(list).toBeHidden() + await expect(address).toHaveValue("github") + await address.press("Escape") + await expect(address).toHaveValue("https://alpha.example/") + await expect.poll(selection).toBe("https://alpha.example/") + await expect(address).toBeFocused() + await address.press("Escape") + await expect(address).not.toBeFocused() + + // A caret that leaves the end takes the completed address into the text: the page stays first, and nothing is selected. + await address.focus() + await address.pressSequentially("gith") + await expect.poll(selection).toBe("ub.com") + await address.press("ArrowRight") + await expect(address).toHaveValue("github.com") + await expect.poll(selection).toBe("") + await expect(addresses.first()).toHaveText("github.com/") + await expect(options.nth(1)).toHaveText("github.com-Google Search") + + // A click opens the row it is on, chosen or not. + await options.nth(2).click() + await expect(address).toHaveValue(/^https:\/\/github\.com\/.+/) + await expect(address).not.toBeFocused() +}) + +story("keeps the address bar working, and says so, while main's history cannot be read or cleared", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Seed history", exact: true }).click() + await root.getByRole("button", { name: "Seed imported history", exact: true }).click() + await root.getByRole("button", { name: "History away", exact: true }).click() + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + const options = page.getByRole("listbox", { name: "Suggestions" }).getByRole("option") + + // Main rejects every question. The list still has the typed text and the window's own last pages. + await address.click() + await address.pressSequentially("localhost") + await expect(options).toHaveCount(2) + await expect(address).toHaveValue("localhost:5173/settings") + // The imported pages are out of reach, so their words find only the search for them, which Enter opens. + await address.fill("") + await address.pressSequentially("rune") + await expect(options).toHaveText(["rune-Google Search"]) + await address.press("Enter") + await expect(address).toHaveValue("https://www.google.com/search?q=rune") + + // Clearing empties the window's list at once and says that main's history stayed. + const clear = async () => { + await root.getByRole("button", { name: "Browser options", exact: true }).click() + await page.getByRole("menuitem", { name: "More tools", exact: true }).click() + await page.getByRole("menuitem", { name: "Clear history", exact: true }).click() + } + + await clear() + await expect(root.getByText("Couldn't clear the history. Try again.", { exact: true })).toBeVisible() + await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible() + // The item stays although the window's list is empty: main's history is still there to clear once it is back. + await root.getByRole("button", { name: "History away", exact: true }).click() + await clear() + await expect(root.getByText("Main history: 0", { exact: true })).toBeVisible() }) story("lists recent pages on a blank tab and opens one", async ({ page }) => { @@ -918,15 +1600,23 @@ story("keeps a page note editable beside a tiny viewport and attaches it to the await width.fill("8") await height.fill("8") await expectSize(root.getByTestId("native-Alpha"), 8, 8) - const field = root.locator('[data-component="browser-address"]') - const add = root.getByRole("button", { name: "Add page to session", exact: true }) - await field.hover() - await add.click() + await addPage(page, root) + const editor = root.locator('[data-slot="browser-comment-editor"] textarea') + await editor.click() + await editor.fill("Check the header layout") + await addPage(page, root) + await expect(editor).toHaveValue("Check the header layout") + await editor.press("Enter") + await expect(root.getByTestId("fixture-comments").getByRole("listitem")).toHaveText([/: Check the header layout$/]) +}) + +story("adds the whole page to the session and keeps the draft when the button is pressed again", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await addPage(page, root) const editor = root.locator('[data-slot="browser-comment-editor"] textarea') await editor.click() await editor.fill("Check the header layout") - await field.hover() - await add.click() + await addPage(page, root) await expect(editor).toHaveValue("Check the header layout") await editor.press("Enter") await expect(root.getByTestId("fixture-comments").getByRole("listitem")).toHaveText([/: Check the header layout$/]) @@ -936,17 +1626,43 @@ story("shows the page's cookies in the site information and clears them", async const root = page.getByTestId("browser-pane-fixture") await root.getByRole("button", { name: "Site information", exact: true }).click() const site = page.getByRole("dialog") + await site.getByRole("button", { name: "Site settings", exact: true }).click() await expect(site).toContainText("3 cookies in use") await site.getByRole("button", { name: "Clear", exact: true }).click() await expect(site).toContainText("0 cookies in use") }) +story("site information opens on the site and its connection, with the rest one step away", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Site information", exact: true }).click() + const site = page.getByRole("dialog") + // First: where the person is and whether the connection is private. Nothing about cookies or agents yet. + await expect(site).toContainText("alpha.example") + await expect(site).toContainText("Connection is secure") + await expect(site).not.toContainText("cookies in use") + const settings = site.getByRole("button", { name: "Site settings", exact: true }) + await settings.click() + // Second: everything else, with the way back holding the keyboard. + await expect(site.getByRole("button", { name: "Back", exact: true })).toBeFocused() + await expect(site).toContainText("3 cookies in use") + await expect(site).toContainText("You stay signed in.") + await expect(site.getByRole("button", { name: "Clear saved files for this site", exact: true })).toBeEnabled() + await expect(site).toContainText("Agents you allow can use this page") + // Escape steps back one view, then closes. + await page.keyboard.press("Escape") + await expect(settings).toBeFocused() + await expect(site).not.toContainText("cookies in use") + await page.keyboard.press("Escape") + await expect(site).toBeHidden() +}) + story("says a failed cookie read failed and reads again on retry", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("button", { name: "Fail next site read", exact: true }).click() await root.getByRole("button", { name: "Site information", exact: true }).click() const site = page.getByRole("dialog") - await expect(site).toContainText("Request failed") + await site.getByRole("button", { name: "Site settings", exact: true }).click() + await expect(site).toContainText("Couldn't read this site's cookies.") const retry = site.getByRole("button", { name: "Try again", exact: true }) await expect(retry).toBeEnabled() await retry.click() @@ -954,6 +1670,27 @@ story("says a failed cookie read failed and reads again on retry", async ({ page await expect(site.getByRole("button", { name: "Clear", exact: true })).toBeEnabled() }) +story("Browser options keeps its original hand-off target until dismissed", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Browser options" }).click() + await page.getByRole("menuitem", { name: "More tools", exact: true }).click() + const handoff = page.getByRole("menuitem", { name: "Open in default browser" }) + await expect(handoff).toBeVisible() + await root.getByRole("button", { name: "Blank page", includeHidden: true }).dispatchEvent("click") + await expect(handoff).toBeVisible() + await handoff.click() + await expect(root.getByText("External:", { exact: true })).toBeAttached() +}) + +story("Browser options says why a disabled hand-off is unavailable", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Blank page", includeHidden: true }).dispatchEvent("click") + await root.getByRole("button", { name: "Browser options" }).click() + await page.getByRole("menuitem", { name: "More tools", exact: true }).click() + await expect(page.getByRole("menuitem", { name: "Open in default browser" })).toBeDisabled() + await expect(page.getByRole("menu").getByText("This page can't open in your default browser", { exact: true })).toBeVisible() +}) + function viewportControls(page: Page) { const root = page.getByTestId("browser-pane-fixture") @@ -1130,8 +1867,19 @@ story("resizes a device with the RTL side grip by pointer and keyboard", async ( await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") await expect(root.locator('img[elementtiming="embed-snapshot"]')).toHaveCount(0) await page.mouse.up() + + const bottomGrip = root.getByRole("separator", { name: "Resize viewport height", exact: true }) + + await expect(grip).toHaveCSS("outline-style", "none") + await bottomGrip.press("Shift+Tab") + await expect(grip).toBeFocused() + await expect(grip).toHaveCSS("outline-offset", "-2px") await grip.press("Shift+ArrowRight") await expect(width).toHaveValue("398") + + await page.keyboard.press("Tab") + await expect(bottomGrip).toBeFocused() + await expect(bottomGrip).toHaveCSS("outline-offset", "-2px") }) story("pins the responsive dimensions when a manual preview scale is selected", async ({ page }) => { @@ -1223,3 +1971,349 @@ story("keeps the selected device and its rotated viewport with its browser tab", await moreDevices.hover() await expect(pixel).toBeChecked() }) + +story("the zoom row sits on the lines the other rows use, and Left and Right move between its buttons", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Browser options", exact: true }).click() + await expect(page.getByRole("menuitem", { name: "Zoom in", exact: true })).toBeVisible() + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + + const edges = await page.evaluate(() => { + const menu = document.querySelector('[data-component="menu-v2-content"]') + const group = menu?.querySelector('[role="group"][aria-labelledby]') + + const label = (text: string) => { + const node = [...(menu?.querySelectorAll('[data-slot="menu-v2-item-content"]') ?? [])].find((item) => item.textContent?.trim() === text)?.firstChild + const range = document.createRange() + + if (node) range.selectNodeContents(node) + + return range.getBoundingClientRect() + } + + const right = (selector: string) => menu?.querySelector(selector)?.getBoundingClientRect().right + + return { + labels: ["Zoom", "Copy link", "More tools"].map((text) => label(text).left), + tops: ["Zoom", "100%"].map((text) => label(text).top), + trailing: [right('[aria-label="Zoom in"]'), right('[data-component="keybind-v2"]'), right('[data-slot="menu-v2-item-chevron"]')], + heights: [group, group?.previousElementSibling].map((row) => row?.getBoundingClientRect().height), + } + }) + + expect(Math.abs(edges.labels[0]! - edges.labels[1]!)).toBeLessThan(0.5) + expect(Math.abs(edges.labels[0]! - edges.labels[2]!)).toBeLessThan(0.5) + expect(Math.abs(edges.tops[0]! - edges.tops[1]!)).toBeLessThan(0.5) + expect(Math.abs(edges.trailing[0]! - edges.trailing[1]!)).toBeLessThan(0.5) + expect(Math.abs(edges.trailing[0]! - edges.trailing[2]!)).toBeLessThan(0.5) + expect(edges.heights[0]).toBe(edges.heights[1]) + + // At 100% there is nothing to reset, so that button is skipped. Down walks the row's buttons in order, as it walks + // every item. + await page.getByRole("menuitem", { name: "Zoom out", exact: true }).focus() + await page.keyboard.press("ArrowRight") + await expect(page.getByRole("menuitem", { name: "Zoom in", exact: true })).toBeFocused() + await page.keyboard.press("ArrowRight") + await expect(page.getByRole("menuitem", { name: "Zoom in", exact: true })).toBeFocused() + await page.keyboard.press("ArrowLeft") + await expect(page.getByRole("menuitem", { name: "Zoom out", exact: true })).toBeFocused() + await page.keyboard.press("ArrowDown") + await page.keyboard.press("ArrowDown") + await expect(page.getByRole("menuitem", { name: "Copy link", exact: true })).toBeFocused() +}) + +story("shows a page dialog in the pane instead of the page, and answers it with Escape", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const native = root.getByTestId("native-Alpha") + // The fixture's controls sit below the pane, outside the viewport. + await root.getByRole("button", { name: "Page confirm", exact: true }).evaluate((element: HTMLElement) => element.click()) + const dialog = page.getByRole("alertdialog", { name: "alpha.example says" }) + await expect(dialog).toContainText("Discard the draft?") + await expect(dialog).toContainText("1 more waiting") + await expect(dialog.getByRole("checkbox", { name: "Stop this page from showing more messages" })).toBeVisible() + // A page blocked in a dialog draws nothing: the native view hides, and the dialog sits over the page's box. + await expect(native).toHaveAttribute("data-visible", "false") + await expect(dialog.getByRole("button", { name: "OK", exact: true })).toBeFocused() + await page.keyboard.press("Escape") + await expect(dialog).toBeHidden() + await expect(root.getByText('Answers: [{"kind":"dialog","accept":false,"text":"","stop":false}]', { exact: true })).toBeVisible() + await expect(native).toHaveAttribute("data-visible", "true") +}) + +story("asks for a site's permission in a bar while the page stays usable", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Permission request", exact: true }).evaluate((element: HTMLElement) => element.click()) + const bar = root.getByRole("alertdialog", { name: "Site permission request" }) + await expect(bar).toContainText("alpha.example wants to show notifications.") + await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") + const always = bar.getByRole("button", { name: "Always allow", exact: true }) + const answered = root.getByText('Answers: [{"kind":"permission","allow":true,"remember":true}]', { exact: true }) + // A page can make the bar appear under a click the user is making: a press right after it appears does nothing. + await always.click() + await expect(bar).toBeVisible() + await expect(root.getByText("Answers: []", { exact: true })).toBeVisible() + // Once the bar has been there long enough to read, a new press answers it. + await expect(async () => { + await always.click({ timeout: 1_000 }) + await expect(answered).toBeVisible({ timeout: 200 }) + }).toPass() + await expect(bar).toBeHidden() +}) + +story("starts the bar's input protection over when the page asks again", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Permission request", exact: true }).evaluate((element: HTMLElement) => element.click()) + const bar = root.getByRole("alertdialog", { name: "Site permission request" }) + const once = bar.getByRole("button", { name: "Allow this time", exact: true }) + await expect(once).toBeVisible() + // The delay is the contract: let the first appearance's run out, so only a restart can refuse the next press. + await page.waitForTimeout(600) + // The page asks again: the same bar shows anew, so a press at once does nothing. + await root.getByRole("button", { name: "Repeat permission request", exact: true }).evaluate((element: HTMLElement) => element.click()) + await once.click() + await expect(bar).toBeVisible() + await expect(root.getByText("Answers: []", { exact: true })).toBeVisible() + await expect(async () => { + await once.click({ timeout: 1_000 }) + await expect(root.getByText('Answers: [{"kind":"permission","allow":true,"remember":false}]', { exact: true })).toBeVisible({ + timeout: 200, + }) + }).toPass() +}) + +story("an agent's show request gives its page's permission bar no press that was on its way to the person's", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Permission request", exact: true }).evaluate((element: HTMLElement) => element.click()) + const bar = root.getByRole("alertdialog", { name: "Site permission request" }) + const once = bar.getByRole("button", { name: "Allow this time", exact: true }) + await expect(bar).toContainText("alpha.example wants to show notifications.") + // The person's bar has been there long enough to answer, so only the change of tab can refuse the next press. + await page.waitForTimeout(600) + const target = (await once.boundingBox())! + // The agent shows its own page, whose first request has the same kind and number as the one on screen. The press + // lands where the person's Allow was, at once. + await root.getByRole("button", { name: "Agent shows a page that asks", exact: true }).evaluate((element: HTMLElement) => element.click()) + await page.mouse.click(target.x + target.width / 2, target.y + target.height / 2) + await expect(root.getByText("Answers: []", { exact: true })).toBeVisible() + await expect(bar).toContainText("second.example wants to use your camera.") + // The tab's answers take no input while its page is held back, then a new press answers the request on screen, in its tab. + await expect(async () => { + await once.click({ timeout: 1_000 }) + await expect(root.getByText('Answered in: ["Second"]', { exact: true })).toBeVisible({ timeout: 200 }) + }).toPass() +}) + +story("an agent's show request leaves the keyboard where the person types, and its tab's bar answers no key or click meanwhile", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + await address.click() + await page.keyboard.type("exa") + await expect(address).toHaveValue(/exa$/) + + // In the page, in one task: the show request, then at once the keys and clicks that would answer its bar. Escape + // and the close button answer "not now", which nothing but the reveal's guard holds back. + const held = await root.getByRole("button", { name: "Agent shows a page that asks", exact: true }).evaluate((show: HTMLElement) => { + show.click() + const bar = document.querySelector('[data-component="browser-prompt"]') + const buttons = Array.from(bar?.querySelectorAll("button") ?? []) + buttons[0]?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })) + buttons.forEach((button) => button.click()) + + return buttons.length + }) + + expect(held).toBeGreaterThan(1) + const bar = root.getByRole("alertdialog", { name: "Site permission request" }) + await expect(bar).toContainText("second.example wants to use your camera.") + await expect(root.getByText("Answers: []", { exact: true })).toBeVisible() + + // The person was typing an address: the rest of it goes to the address field, not to the window or the composer. + await expect(address).toBeFocused() + await page.keyboard.type("mple") + await expect(address).toHaveValue(/mple$/) + await expect(root.getByRole("textbox", { name: "Composer stand-in" })).toHaveValue("") +}) + +story("takes the keyboard from the window for a dialog and gives it back where it was", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const composer = root.getByRole("textbox", { name: "Composer stand-in" }) + await composer.focus() + await root.getByRole("button", { name: "Page confirm", exact: true }).evaluate((element: HTMLElement) => element.click()) + const dialog = page.getByRole("alertdialog", { name: "alpha.example says" }) + await expect(dialog.getByRole("button", { name: "OK", exact: true })).toBeFocused() + await page.keyboard.press("Escape") + await expect(dialog).toBeHidden() + await expect(composer).toBeFocused() +}) + +story("asks again for an agent's request without offering to keep the answer, and says why", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Agent permission request", exact: true }).evaluate((element: HTMLElement) => element.click()) + const bar = root.getByRole("alertdialog", { name: "Site permission request" }) + await expect(bar).toContainText("alpha.example wants to use your microphone.") + await expect(bar).toContainText("The agent is working in this tab. Your answer applies this one time.") + await expect(bar.getByRole("button", { name: "Always allow", exact: true })).toHaveCount(0) + await expect(bar.getByRole("button", { name: "Allow this time", exact: true })).toBeVisible() + // Enter on the bar never grants: focus starts on the refusing button. + await bar.getByRole("button", { name: "Block", exact: true }).focus() + await expect(async () => { + await page.keyboard.press("Enter") + await expect(root.getByText('Answers: [{"kind":"permission","allow":false,"remember":false}]', { exact: true })).toBeVisible({ + timeout: 200, + }) + }).toPass() +}) + +story("asks for a page's prompt text and sends what the user typed", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Page prompt", exact: true }).evaluate((element: HTMLElement) => element.click()) + const dialog = page.getByRole("alertdialog", { name: "alpha.example says" }) + await expect(dialog).toContainText("Name the copy") + const field = dialog.getByRole("textbox", { name: "Your answer" }) + await expect(field).toHaveValue("Draft") + await expect(field).toHaveAttribute("maxlength", "2000") + await field.fill("Final copy") + const answered = root.getByText('Answers: [{"kind":"dialog","accept":true,"text":"Final copy","stop":false}]', { exact: true }) + await expect(async () => { + await field.press("Enter") + await expect(answered).toBeVisible({ timeout: 200 }) + }).toPass() + await expect(dialog).toBeHidden() +}) + +// What the key test below records in the story's window. +declare global { + interface Window { + keyLog: KeyboardEvent[] + keyBehind: string[] + } +} + +story("keeps the keys inside a page prompt, and leaves them to the window once the keyboard is elsewhere", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + // Each key as the window saw it first, and whether its default was cancelled once every handler had seen it. + await page.evaluate(() => { + const log: KeyboardEvent[] = [] + // Keys the window's own handlers behind the prompt would see, as the composer's and the zoom's do. + const behind: string[] = [] + Object.assign(window, { keyLog: log, keyBehind: behind }) + window.addEventListener("keydown", (event) => log.push(event), { capture: true }) + window.addEventListener("keydown", (event) => behind.push(event.key)) + }) + const behind = () => page.evaluate(() => window.keyBehind.splice(0)) + + const log = () => + page.evaluate(() => + window.keyLog + .splice(0) + .filter((event) => !["Control", "Alt", "Shift", "Meta"].includes(event.key)) + .map((event) => `${event.key}:${event.defaultPrevented ? "prevented" : "default"}`), + ) + + await root.getByRole("button", { name: "Page prompt", exact: true }).evaluate((element: HTMLElement) => element.click()) + const dialog = page.getByRole("alertdialog", { name: "alpha.example says" }) + const field = dialog.getByRole("textbox", { name: "Your answer" }) + await expect(field).toBeFocused() + await field.press("End") + await page.keyboard.type(" two") + await log() + + // Reload, the agent switch, find, close and new tab, zoom and history do nothing here. + for (const chord of ["Control+r", "Control+.", "Control+f", "Control+w", "Control+t", "Control+Equal", "Alt+ArrowLeft", "F5"]) + await page.keyboard.press(chord) + expect(await log()).toEqual(["r", ".", "f", "w", "t", "=", "ArrowLeft", "F5"].map((key) => `${key}:prevented`)) + // Editing keys edit the field as they do anywhere. + await page.keyboard.press("Control+a") + await page.keyboard.press("ArrowRight") + await page.keyboard.press("Backspace") + expect(await log()).toEqual(["a:default", "ArrowRight:default", "Backspace:default"]) + await expect(field).toHaveValue("Draft tw") + await expect(dialog).toBeVisible() + // None of them went past the prompt to the window's handlers. + expect(await behind()).toEqual([]) + + // With the keyboard in the composer, its keys are the app's and the prompt stays open. + await root.getByRole("textbox", { name: "Composer stand-in" }).focus() + await page.keyboard.press("Control+r") + expect(await log()).toEqual(["r:default"]) + expect(await behind()).toEqual(["Control", "r"]) + await expect(dialog).toBeVisible() + + await field.focus() + await expect(async () => { + await field.press("Enter") + await expect(root.getByText('Answers: [{"kind":"dialog","accept":true,"text":"Draft tw","stop":false}]', { exact: true })).toBeVisible({ + timeout: 200, + }) + }).toPass() +}) + +story("asks for a site's sign-in with its realm, says the last one failed, and keeps nothing on cancel", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Sign-in request", exact: true }).evaluate((element: HTMLElement) => element.click()) + const dialog = page.getByRole("alertdialog", { name: "Sign in to intranet.alpha.example" }) + // The realm sits in its sentence inside directional isolates. + await expect(dialog).toContainText(/The site says: “\u2068Staff area\u2069”/) + await expect(dialog.getByRole("alert")).toBeVisible() + const user = dialog.getByRole("textbox", { name: "User name" }) + await expect(user).toBeFocused() + await expect(user).toHaveAttribute("maxlength", "1024") + await user.fill("demo") + await dialog.getByLabel("Password").fill("secret") + await page.keyboard.press("Escape") + await expect(dialog).toBeHidden() + await expect(root.getByText('Answers: [{"kind":"dismiss"}]', { exact: true })).toBeVisible() +}) + +story("the options menu lists everyday actions first and the rest under More tools, where each still runs", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Seed history", exact: true }).click() + await root.getByRole("button", { name: "Seed imported history", exact: true }).click() + await expect(root.getByText(/^Visits: \S/)).toBeVisible() + await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible() + await root.getByRole("button", { name: "Browser options", exact: true }).click() + // Find, the zoom row (out, the zoom itself, in), Copy link and Add page; then More tools; then settings. + await expect(page.getByRole("menu").first().getByRole("menuitem")).toHaveText([ + /^Find in page/, + "", + "100%", + "", + "Copy link", + "Add page to session", + "More tools", + "Browser settings", + ]) + await expect(page.getByRole("group", { name: "Zoom", exact: true }).getByRole("menuitem")).toHaveCount(3) + await page.getByRole("menuitem", { name: "More tools", exact: true }).click() + await expect(page.getByRole("menu", { name: "More tools", exact: true }).getByRole("menuitem")).toHaveText([ + /^Comment on part of the page/, + "Open in default browser", + /^Reload without saved files/, + "Clear history", + ]) + // Clearing forgets the window's last pages and main's history, imported pages included. + await page.getByRole("menuitem", { name: "Clear history", exact: true }).click() + await expect(root.getByText("Visits:", { exact: true })).toBeVisible() + await expect(root.getByText("Main history: 0", { exact: true })).toBeVisible() + // The bar keeps only what every browser has there. + await expect(root.getByRole("button", { name: "Add page to session", exact: true })).toHaveCount(0) + await expect(root.getByRole("button", { name: "Comment on part of the page", exact: true })).toHaveCount(0) +}) + +// The comment tool lives under Browser options > More tools. While it waits for a pick, the pane says so in a status +// line for assistive technology, which these cases read where the old toolbar button had a pressed state. +function commentTool(page: Page, root: Locator) { + return { + click: async () => { + await root.getByRole("button", { name: "Browser options", exact: true }).click() + await page.getByRole("menuitem", { name: "More tools", exact: true }).click() + await page.getByRole("menuitem", { name: /^Comment on part of the page/ }).click() + }, + picking: root.getByText("Click part of the page to comment on it. Press Escape to cancel.", { exact: true }), + } +} + +async function addPage(page: Page, root: Locator) { + await root.getByRole("button", { name: "Browser options", exact: true }).click() + await page.getByRole("menuitem", { name: "Add page to session", exact: true }).click() +} diff --git a/packages/app/component-tests/browser-settings.spec.ts b/packages/app/component-tests/browser-settings.spec.ts new file mode 100644 index 000000000000..6c8707c282fb --- /dev/null +++ b/packages/app/component-tests/browser-settings.spec.ts @@ -0,0 +1,194 @@ +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; historyKept?: 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, + historyKept: input.options?.historyKept, + }) + }, + { 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("no setting decides what an import brings: the import section has its browsers and no note, and Advanced no switch for it", async ({ page }) => { + const view = await open(page, { target: "settings-browser-remote", extensions: true }) + const section = view.root.getByRole("region", { name: "Import from another browser", exact: true }) + + // The section is its title and one row per browser, whose button opens the import dialog with its two boxes. + await expect(section.getByRole("button", { name: "Import…", exact: true })).toHaveCount(2) + await expect(section.locator("p")).toHaveCount(0) + await expect(view.advanced).toHaveAttribute("aria-expanded", "true") + // Advanced holds two switches, neither of them about importing. + await expect(view.root.getByRole("switch")).toHaveCount(3) + await expect(view.root.getByRole("switch", { name: /history/i })).toHaveCount(0) + await expect(view.stored).not.toContainText("importHistory") +}) + +story("a sign-out that left the history behind says so in its row, and still forgets the window's last pages", async ({ page }) => { + const view = await open(page, { target: "settings-browser-cookies", historyKept: true }) + + await expect(view.root.getByTestId("browser-settings-visits")).toHaveText("1") + await view.root.getByRole("button", { name: "Sign out everywhere", exact: true }).click() + // The sign-out itself worked, so the row does not call it failed; "everywhere" alone would be a false claim. + await expect(view.root.getByText("Signed out everywhere. The history could not be cleared.", { exact: true })).toBeVisible() + await expect(view.root.getByTestId("browser-settings-visits")).toHaveText("0") + await expect(view.root.getByRole("button", { name: "Sign out everywhere", exact: true })).toBeEnabled() +}) + +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) +}) diff --git a/packages/app/component-tests/browser-site-chooser.spec.ts b/packages/app/component-tests/browser-site-chooser.spec.ts new file mode 100644 index 000000000000..c5e52f8fa06f --- /dev/null +++ b/packages/app/component-tests/browser-site-chooser.spec.ts @@ -0,0 +1,569 @@ +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 + pages?: number +} + +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" until the person changes which sites come, then how many sites it brings. + importButton: dialog.getByRole("button", { name: /^Import( [\d,]+ sites?)?$/ }), + // What comes over: two real checkboxes, ticked until the person unticks one. + signins: dialog.getByRole("checkbox", { name: "Sign-ins", exact: true }), + history: dialog.getByRole("checkbox", { name: "Browsing history", exact: true }), + 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() + expect(await view.options.count()).toBeLessThan(45) + await expect(view.importButton).toHaveText("Import") + + // The two boxes come before the search in reading order. 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("Shift+Tab") + await expect(view.history).toBeFocused() + await page.keyboard.press("Shift+Tab") + await expect(view.signins).toBeFocused() + await page.keyboard.press("Tab") + await page.keyboard.press("Tab") + 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"], cookies: true, history: true })]) + 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, brings its sign-in alone, and stays open to say that some stayed behind", async ({ page }) => { + const view = await open(page, { sites: 5, site: { name: "github.com", choose: true }, partial: true, pages: 4210 }) + + 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") + // This dialog is about one site's sign-in: it offers no boxes, and asks main for no history. + await expect(view.dialog.getByRole("checkbox")).toHaveCount(0) + await view.importButton.click() + await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", sites: ["github.com"], cookies: true, history: false })]) + const status = view.dialog.getByRole("status") + await expect(status).toHaveText("Imported from Google Chrome. Some sites will ask you to sign in again.") + 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") + // A row is the site's name and nothing else. + await expect(view.dialog.locator('[data-site="google.com"]')).toHaveText("google.com") +}) + +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() +}) + +// Where the two boxes are in the dialog, in CSS pixels: each box's left edge and label against the title's left edge, +// each 28px row's top from the dialog's top, and how far the first box's focus ring (a 2px outline, 2px off the 16px +// box) stays inside what clips the body. +const boxes = (dialog: ReturnType) => + dialog.evaluate((node) => { + const text = (element: Element | null) => { + const range = document.createRange() + + if (element) range.selectNodeContents(element) + + return range.getBoundingClientRect() + } + + const container = (node.closest('[data-slot="dialog-container"]') ?? node).getBoundingClientRect() + const title = text(node.querySelector('[data-slot="dialog-title"]')) + const clip = node.querySelector('[data-slot="dialog-body"] [data-scrollable]')?.getBoundingClientRect() + const kinds = Array.from(node.querySelectorAll('[data-slot="dialog-body"] [data-slot="checkbox-v2"]:not([aria-hidden])')) + const controls = kinds.map((kind) => kind.querySelector('[data-slot="checkbox-v2-control"]')?.getBoundingClientRect()) + const first = controls[0] + const last = controls[controls.length - 1] + + return { + left: controls.map((control) => Math.round((control?.left ?? -1) - title.left)), + label: kinds.map((kind) => Math.round(text(kind.querySelector('[data-slot="checkbox-v2-label"]')).left - title.left)), + top: kinds.map((kind) => Math.round((kind.parentElement?.getBoundingClientRect().top ?? -1) - container.top)), + height: kinds.map((kind) => kind.parentElement?.getBoundingClientRect().height), + ring: clip && first && last ? [first.left - 4 - clip.left, first.top - 4 - clip.top, clip.bottom - last.bottom - 4].map((value) => Math.round(value)) : [], + } + }) + +story("opens on two ticked boxes and Import, which brings everything without the list", async ({ page }) => { + const view = await open(page, { sites: 5, reveal: false, pages: 4210 }) + + // No sentence: the title, the two boxes and the buttons say it. + await expect(view.signins).toBeChecked() + await expect(view.history).toBeChecked() + await expect(view.dialog.locator('[data-slot="dialog-description"]')).toHaveCount(0) + await expect(view.list).toHaveCount(0) + await expect(view.dialog.getByRole("button", { name: "Choose sites" })).toHaveAttribute("aria-expanded", "false") + await expect(view.importButton).toHaveText("Import") + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + const collapsed = await boxes(view.dialog) + + // Both boxes start on the title's left edge, in 28px rows, with their focus ring inside the body's clip. + expect(collapsed).toMatchObject({ left: [0, 0], label: [24, 24], height: [28, 28] }) + expect(Math.min(...collapsed.ring)).toBeGreaterThanOrEqual(0) + + // "Choose sites" opens the list under the boxes, which stay where they are. + await view.dialog.getByRole("button", { name: "Choose sites" }).click() + await expect(view.options).toHaveCount(5) + const expanded = await boxes(view.dialog) + expect(expanded).toMatchObject({ left: [0, 0], label: [24, 24], height: [28, 28], top: collapsed.top }) + expect(Math.min(...expanded.ring)).toBeGreaterThanOrEqual(0) + await view.dialog.getByRole("button", { name: "Choose sites" }).click() + await expect(view.list).toHaveCount(0) + + await view.importButton.click() + // No list of sites: main imports the whole profile, its sign-ins and its history. + await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: true, history: true })]) + await expect(view.record).toHaveAttribute("data-closed", "true") +}) + +story("a box the person unticks stays behind, Import needs one of them, and Enter on a box imports", async ({ page }) => { + const view = await open(page, { sites: 5, reveal: false, pages: 4210 }) + + // The dialog opens with the focus on itself. Tab reaches the boxes in reading order, after Close; Space toggles the + // one that has the focus. + await expect(view.dialog.locator('[data-slot="dialog-content"]').or(view.dialog)).toBeFocused() + await page.keyboard.press("Tab") + await expect(view.dialog.getByRole("button", { name: "Close", exact: true })).toBeFocused() + await page.keyboard.press("Tab") + await expect(view.signins).toBeFocused() + await page.keyboard.press("Space") + await expect(view.signins).not.toBeChecked() + await page.keyboard.press("Tab") + await expect(view.history).toBeFocused() + await page.keyboard.press("Space") + await expect(view.history).not.toBeChecked() + // Nothing is ticked: there is nothing to import, by the button or by Enter. + await expect(view.importButton).toBeDisabled() + await page.keyboard.press("Enter") + await expect(view.record.locator("li")).toHaveCount(0) + + // History alone: no cookie is asked for. + await page.keyboard.press("Space") + await expect(view.importButton).toBeEnabled() + await page.keyboard.press("Enter") + await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: false, history: true })]) + await expect(view.record).toHaveAttribute("data-closed", "true") +}) + +story("with Browsing history unticked the import brings sign-ins alone, of the chosen sites", async ({ page }) => { + const view = await open(page, { sites: 5 }) + + // A click on the label unticks its box. + await view.dialog.getByText("Browsing history", { exact: true }).click() + await expect(view.history).not.toBeChecked() + await view.dialog.locator('[data-site="github.com"]').click() + await expect(view.importButton).toHaveText("Import 4 sites") + await view.importButton.click() + const sent = JSON.parse((await view.record.locator("li").textContent()) ?? "{}") + expect(sent).toMatchObject({ cookies: true, history: false }) + expect(sent.sites).toHaveLength(4) +}) + +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 from another browser" }) + 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") + 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") + 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() + + expect(box && name && box.x > name.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 offer, as a bar over a page or a card on the new tab page, with what the faked profile answers an import. +async function offer(page: Page, scenario: SiteScenario, card = false) { + await page.evaluate( + async (input) => { + const [{ mountSiteChooser }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)]) + + mountSiteChooser({ ui, scenario: input.scenario, offer: true, card: input.card }) + }, + { modules, scenario, card }, + ) + + return { + importing: page.getByRole("button", { name: "Import", exact: true }), + confirmation: page.getByRole("status").filter({ hasText: /^Imported/ }), + record: page.getByTestId("site-chooser-imports"), + } +} + +story("the sign-in bar names the browser, imports sign-ins and history in one click, and says in words what came", async ({ page }) => { + const bar = await offer(page, { sites: 5, pages: 4210 }) + + await expect(page.getByText("Bring your sign-ins and history from Google Chrome · Work", { exact: true })).toBeVisible() + await bar.importing.click() + // No dialog and no boxes here: the one click brings both. + await expect(bar.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: true, history: true })]) + await expect(bar.confirmation).toHaveText("Imported sign-ins and history from Google Chrome") + await expect(bar.record).toHaveAttribute("data-imported", "1") +}) + +story("the sign-in bar says that some sites will ask again when sign-ins stayed behind", async ({ page }) => { + const bar = await offer(page, { sites: 5, pages: 4210, protected: 3 }) + + await bar.importing.click() + await expect(bar.confirmation).toHaveText("Imported from Google Chrome. Some sites will ask you to sign in again.") +}) + +story("the bar's own dialog brings history alone when Sign-ins is unticked, and the bar says so without loading the page again", async ({ page }) => { + const bar = await offer(page, { sites: 5, pages: 4210 }) + + await page.getByRole("button", { name: "Import from another browser", exact: true }).click() + await page.getByRole("menuitem", { name: "Choose sites to import", exact: true }).click() + const dialog = page.getByRole("dialog", { name: /^Import from Google Chrome/ }) + await dialog.getByText("Sign-ins", { exact: true }).click() + await expect(dialog.getByRole("checkbox", { name: "Sign-ins", exact: true })).not.toBeChecked() + await dialog.getByRole("button", { name: "Import", exact: true }).click() + await expect(bar.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: false, history: true })]) + await expect(dialog).toHaveCount(0) + await expect(bar.confirmation).toHaveText("Imported history from Google Chrome") + // No sign-in came, so the page has nothing new to load with. + await expect(bar.record).toHaveAttribute("data-imported", "0") +}) + +story("the offer card has a title and no paragraph, and its Import brings both", async ({ page }) => { + const card = await offer(page, { sites: 5, pages: 4210 }, true) + const region = page.getByRole("region", { name: "Bring your sign-ins and history", exact: true }) + + await expect(region.getByText("Bring your sign-ins and history", { exact: true })).toBeVisible() + await expect(region.getByText(/Copy your sign-ins/)).toHaveCount(0) + await region.getByRole("button", { name: "Import", exact: true }).first().click() + await expect(card.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: true, history: true })]) + await expect(card.confirmation).toHaveText("Imported sign-ins and history from Google Chrome") +}) + +// 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() + // No history in this profile: the line names the sign-ins alone. + const { record, confirmation, importing } = await offer(page, { sites: 5, skipped: 318 }) + await expect(confirmation).toHaveCount(0) + + // 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") +}) diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index 3fb3fde481d1..028652b408f9 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -1,5 +1,22 @@ import { expect, story } from "../../stories/playwright/story" +story("outsets the Send ring without changing the scrolling toolbar rings", async ({ mount, page }) => { + const component = await mount("opencode-composer-flow--toolbar-overflow", { args: { alternate: "none" } }) + + const send = component.locator('[data-action="composer-submit"]') + + const variant = component.getByRole("button", { name: "Choose model variant" }) + + await expect(send).toBeEnabled() + await send.press("Shift+Tab") + await expect(variant).toBeFocused() + await expect(variant).toHaveCSS("outline-offset", "-2px") + await page.keyboard.press("Tab") + await expect(send).toBeFocused() + await expect(send).toHaveCSS("outline-style", "solid") + await expect(send).toHaveCSS("outline-offset", "2px") +}) + story("cycles full prompts with plain arrows without opening the picker", async ({ mount, page }) => { const component = await mount("opencode-composer-flow--prompt-history") const input = component.getByRole("textbox", { name: "Prompt", exact: true }) diff --git a/packages/app/component-tests/focus-rescue.fixture.tsx b/packages/app/component-tests/focus-rescue.fixture.tsx new file mode 100644 index 000000000000..313cdbd7b9cc --- /dev/null +++ b/packages/app/component-tests/focus-rescue.fixture.tsx @@ -0,0 +1,30 @@ +import { installFocusRescue } from "@opencode/ui/context/focus-rescue" + +/** Scopes whose buttons remove themselves when pressed, all but the opener. */ +export function mountFocusRescue() { + const host = document.createElement("div") + host.dataset.testid = "focus-rescue-fixture" + host.innerHTML = ` +
+ + + +
+ +
+ +
+
+
+ + + +
+
+ ` + host.addEventListener("click", (event) => { + if (event.target instanceof HTMLButtonElement && event.target.dataset.testid !== "opener") event.target.remove() + }) + document.body.appendChild(host) + installFocusRescue() +} diff --git a/packages/app/component-tests/focus-rescue.spec.ts b/packages/app/component-tests/focus-rescue.spec.ts new file mode 100644 index 000000000000..3fd89a10d985 --- /dev/null +++ b/packages/app/component-tests/focus-rescue.spec.ts @@ -0,0 +1,44 @@ +import type { Locator } from "@playwright/test" +import { expect, sourceURL, story } from "../../stories/playwright/story" + +const fixture = sourceURL(new URL("./focus-rescue.fixture.tsx", import.meta.url)) + +story.beforeEach(async ({ mount, page }) => { + // Any story loads the app's styles; the fixture mounts its scopes beside it. + await mount("ui-line-comment--editor") + await page.evaluate(async (fixture) => { + const { mountFocusRescue } = await import(fixture) + mountFocusRescue() + }, fixture) +}) + +const ringed = (locator: Locator) => locator.evaluate((element) => element.matches(":focus-visible")) + +story("moves focus to the next item, or to the previous one after the last", async ({ page }) => { + const list = page.getByTestId("list") + + await list.getByRole("button", { name: "Two" }).focus() + await page.keyboard.press("Enter") + await expect(list.getByRole("button", { name: "Three" })).toBeFocused() + expect(await ringed(list.getByRole("button", { name: "Three" }))).toBe(true) + + await page.keyboard.press("Enter") + await expect(list.getByRole("button", { name: "One" })).toBeFocused() +}) + +story("returns focus to what had it before when a scope is left empty", async ({ page }) => { + await page.getByTestId("opener").focus() + await page.getByTestId("toasts").getByRole("button", { name: "Toast" }).focus() + await page.keyboard.press("Enter") + + await expect(page.getByTestId("opener")).toBeFocused() +}) + +story("never moves focus into a tab list", async ({ page }) => { + await page.getByTestId("opener").focus() + await page.getByTestId("strip").getByRole("tab", { name: "Tab B" }).focus() + await page.keyboard.press("Enter") + + // Tab A and Add tab are still there, but a tab list's tabs select themselves on focus. + await expect(page.getByTestId("opener")).toBeFocused() +}) diff --git a/packages/app/component-tests/input-surfaces.spec.ts b/packages/app/component-tests/input-surfaces.spec.ts index 1cce08660c43..eac17f90785e 100644 --- a/packages/app/component-tests/input-surfaces.spec.ts +++ b/packages/app/component-tests/input-surfaces.spec.ts @@ -1,5 +1,93 @@ import { expect, story } from "../../stories/playwright/story" +story("active search options keep their system highlight in forced colours", async ({ mount, page }) => { + await page.emulateMedia({ forcedColors: "active" }) + + const root = await mount("review-focus-visibility--all-surfaces", { args: { forced: false } }) + + const highlight = await page.evaluate(() => { + const probe = document.createElement("span") + + probe.style.backgroundColor = "Highlight" + probe.style.color = "HighlightText" + document.body.append(probe) + const style = getComputedStyle(probe) + + const result = { background: style.backgroundColor, color: style.color } + + probe.remove() + + return result + }) + + for (const name of [ + "Palette: active option loses contrast", + "Search list: active option loses contrast", + "Home search results: Shift+Tab reaches", + ]) { + const card = root.locator("figure").filter({ hasText: name }) + + const active = card.locator("[data-active]") + + const input = card.getByRole("combobox") + + await expect(active).toHaveCSS("background-color", highlight.background) + await expect(active.getByText("Active option")).toHaveCSS("color", highlight.color) + await input.press("ArrowDown") + await expect(input).toBeFocused() + await expect(active).toHaveText("Next option") + await expect(active).toHaveCSS("background-color", highlight.background) + } +}) + +story("focus-only outlines stay off at rest in forced colours", async ({ mount, page }) => { + await page.emulateMedia({ forcedColors: "active" }) + + const root = await mount("review-focus-visibility--all-surfaces", { args: { forced: false, locator: false } }) + + const controls = [ + { + card: "Switch: a black ring flashes", + target: '[data-slot="switch-input"]', + ring: '[data-slot="switch-control"]', + hasBorder: true, + }, + { + card: "Radio: forced colours show a ring", + target: '[data-slot="radio-v2-item-input"][value="text"]', + ring: '[data-slot="radio-v2-item"][data-checked] [data-slot="radio-v2-item-control"]', + hasBorder: true, + }, + { + card: "Language: inline select", + target: '[data-component="select-v2"]', + ring: '[data-component="select-v2"]', + hasBorder: false, + }, + ] + + for (const control of controls) { + const card = root.locator("figure").filter({ hasText: control.card }) + + const target = card.locator(control.target) + + const ring = card.locator(control.ring) + + await expect(ring).toHaveCSS("outline-style", "none") + + if (control.hasBorder) await expect(ring).toHaveCSS("border-top-width", "1px") + + await target.press("Shift+Tab") + await page.keyboard.press("Tab") + await expect(target).toBeFocused() + await expect(ring).toHaveCSS("outline-style", "solid") + await expect(ring).toHaveCSS("outline-width", "2px") + await expect(ring).not.toHaveCSS("transition-property", /outline|all/) + await page.keyboard.press("Shift+Tab") + await expect(ring).toHaveCSS("outline-style", "none") + } +}) + for (const control of ["text-input", "textarea"]) { story(`${control} supports its surfaces with inset feedback and stable geometry`, async ({ mount, page }) => { const root = await mount(`ui-${control}--surfaces`) diff --git a/packages/app/component-tests/plugin-host.fixture.tsx b/packages/app/component-tests/plugin-host.fixture.tsx index a83d3bb76614..4d9981009845 100644 --- a/packages/app/component-tests/plugin-host.fixture.tsx +++ b/packages/app/component-tests/plugin-host.fixture.tsx @@ -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() {}, diff --git a/packages/app/component-tests/plugin-host.spec.ts b/packages/app/component-tests/plugin-host.spec.ts index 5dc395284eae..6b7194155903 100644 --- a/packages/app/component-tests/plugin-host.spec.ts +++ b/packages/app/component-tests/plugin-host.spec.ts @@ -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 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( diff --git a/packages/app/component-tests/session-containment.fixture.tsx b/packages/app/component-tests/session-containment.fixture.tsx new file mode 100644 index 000000000000..629f70f76efd --- /dev/null +++ b/packages/app/component-tests/session-containment.fixture.tsx @@ -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( + () => ( + + + + + + + } + > + + + + + + + + ), + host, + ) +} + +/** The permission is answered: the dock gives way to the composer. */ +export function answerPermission() { + setPending(false) +} diff --git a/packages/app/component-tests/session-containment.spec.ts b/packages/app/component-tests/session-containment.spec.ts new file mode 100644 index 000000000000..022c521777df --- /dev/null +++ b/packages/app/component-tests/session-containment.spec.ts @@ -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": `
${marker}: the whole answer
`, + "fixed transparent anchor": `${marker}x`, + "popover cover": `${marker}
COVER
`, + "invoker dialog": `${marker}COVER`, + "fixed tint": `${marker}
x
`, + "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\nSample image\n\nTeal text` + +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, 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 } + }) +} diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts index 4e819b704ae0..c03249ee44ae 100644 --- a/packages/app/e2e/regression/composer.spec.ts +++ b/packages/app/e2e/regression/composer.spec.ts @@ -5,6 +5,43 @@ import { mockPluginsActivating, type MockServerConfig } from "../utils/mock-serv test.use({ permissions: ["clipboard-read", "clipboard-write"] }) +test("the composer preserves its ring on dialog return and leaves autofocus and clicks quiet", async ({ page }) => { + const view = await openSession(page, { name: "ComposerKeyboardFocus" }) + + const frame = page.locator('[data-component="composer"]').filter({ has: view.editor }) + + await expect(view.editor).toBeFocused() + await expect(frame).toHaveCSS("outline-style", "none") + + await page.keyboard.press("Shift+Tab") + await expect(view.editor).not.toBeFocused() + await page.keyboard.press("Tab") + await expect(view.editor).toBeFocused() + await expect(frame).toHaveCSS("outline-style", "solid") + + const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) + + const dialog = page.getByRole("dialog") + + await page.keyboard.press(`${modifier}+Shift+p`) + await expect(dialog.getByRole("combobox")).toBeFocused() + await page.keyboard.press("Escape") + await expect(view.editor).toBeFocused() + await expect(frame).toHaveCSS("outline-style", "solid") + + await view.editor.click() + await expect(view.editor).toBeFocused() + await expect(frame).toHaveCSS("outline-style", "none") + await page.keyboard.type("Still quiet") + await expect(frame).toHaveCSS("outline-style", "none") + await page.keyboard.press(`${modifier}+Shift+p`) + await expect(dialog.getByRole("combobox")).toBeFocused() + await page.mouse.click(20, 200) + await expect(dialog).toBeHidden() + await expect(view.editor).toBeFocused() + await expect(frame).toHaveCSS("outline-style", "none") +}) + test("mention a session by title, send its stable token, and open its own tab", async ({ page }) => { const target = "ses_0123456789abcdefghijklmnop" const prompts: Parameters>[0]["body"][] = [] @@ -390,6 +427,9 @@ for (const action of ["tray", "picker"] as const) { }) await expect(page.getByText("Refactor the parser", { exact: true })).toBeVisible() + // Loading the selected model clears the tray, just like switching models does. + const modelButton = page.locator('[data-action="composer-model"]') + await expect(modelButton).toContainText("GLM-5 Go") // The refusal OpenCode Console sends a Go subscriber at a limit, as core records it. const body = { @@ -436,13 +476,13 @@ for (const action of ["tray", "picker"] as const) { if (action === "tray") await tray.getByRole("button", { name: "Switch to a free model", exact: true }).click() if (action === "picker") { - await page.locator('[data-action="composer-model"]').click() + await modelButton.click() const picker = page.getByRole("dialog", { name: "Select model", exact: true }) await picker.getByRole("combobox", { name: "Search models", exact: true }).fill("Big Pickle") await picker.getByRole("option", { name: /Big Pickle/ }).click() } - await expect(page.locator('[data-action="composer-model"]')).toContainText("Big Pickle") + await expect(modelButton).toContainText("Big Pickle") await expect(tray).toHaveCount(0) await expect(view.editor).toHaveText("Refactor the parser") }) diff --git a/packages/app/e2e/regression/home.spec.ts b/packages/app/e2e/regression/home.spec.ts index 4967863850c5..d5013068a635 100644 --- a/packages/app/e2e/regression/home.spec.ts +++ b/packages/app/e2e/regression/home.spec.ts @@ -28,6 +28,76 @@ async function openHome(page: Page, input: Parameters await page.goto("/") } +test("Home projects, utility rows, search and recent sessions show keyboard focus", async ({ page }) => { + const workspace = await mockWorkspace(page, { name: "HomeFocus" }) + + await seed(page, { usedProjects: { local: [workspace.projectID] } }) + await page.goto("/") + + const projects = page.getByRole("complementary", { name: "Projects" }) + + const viewport = page.getByRole("main").getByRole("region", { name: "scrollable content", exact: true }) + + const projectButton = projects.getByRole("button", { name: /HomeFocus/ }) + + const settings = projects.getByRole("button", { name: "Settings", exact: true }) + + const help = projects.getByRole("button", { name: "Help", exact: true }) + + await expect(projectButton).toBeVisible() + await expect(viewport).toHaveAttribute("tabindex", "-1") + await projects.getByRole("button", { name: "Add project", exact: true }).press("Tab") + await expect(projectButton).toBeFocused() + await expect + .poll(() => + projectButton.evaluate((button) => { + const row = button.closest("[data-home-row]") + + return row && getComputedStyle(row, "::after").outlineStyle + }), + ) + .toBe("solid") + + // The two project row actions come before the utility buttons. + await page.keyboard.press("Tab") + await page.keyboard.press("Tab") + await page.keyboard.press("Tab") + await expect(settings).toBeFocused() + await expect(settings).toHaveCSS("outline-style", "solid") + await page.keyboard.press("Tab") + await expect(help).toBeFocused() + await expect(help).toHaveCSS("outline-style", "solid") + + const search = page.getByRole("textbox", { name: "Search sessions", exact: true }) + + const field = page.locator('[data-slot="home-session-search-field"]') + + await page.keyboard.press("Tab") + await expect(search).toBeFocused() + await expect(field).toHaveCSS("outline-style", "solid") + await search.click() + await expect(search).toBeFocused() + await expect(field).toHaveCSS("outline-style", "none") + + const recent = page.getByRole("region", { name: "Recent sessions" }) + + const sessionRow = row(page, "HomeFocus") + + await sessionRow.hover() + await expect(sessionRow).toHaveCSS("outline-style", "none") + await recent.getByRole("button", { name: "New session", exact: true }).press("Tab") + await expect(sessionRow).toBeFocused() + await expect(sessionRow).toHaveCSS("outline-style", "solid") + await expect(sessionRow).toHaveCSS("outline-offset", "-2px") + + await page.setViewportSize({ width: 1280, height: 200 }) + await expect(viewport).toHaveAttribute("tabindex", "0") + await viewport.press("Shift+Tab") + await page.keyboard.press("Tab") + await expect(viewport).toBeFocused() + await expect(viewport).toHaveCSS("outline-offset", "-2px") +}) + test("Home keeps the session list in every interface mode", async ({ page }) => { const earlier = { id: "ses_home_earlier", title: "Finished earlier" } await mockWorkspace(page, { name: "Home", sessions: [earlier] }) @@ -148,7 +218,7 @@ test("the session context menu renames, exports, and deletes a Home session", as await renamedRow.click() await expect(page).toHaveURL(new RegExp(`/session/${fixture.targetID}$`)) await expect(page.locator('[data-slot="titlebar-tabs"] a').filter({ hasText: "Renamed from Home" })).toBeVisible() - await page.getByRole("button", { name: "Home" }).click() + await page.getByRole("button", { name: "Home", exact: true }).click() await expect(page).toHaveURL("/") await renamedRow.click({ button: "right" }) @@ -230,6 +300,17 @@ test("tabbing out of session search closes its results, and tabbing back reopens await page.keyboard.press("Shift+Tab") await expect(search).toBeFocused() await expect(panel.getByRole("option")).toContainText(earlier.title) + + // The results are active descendants, not independent Tab stops before the search input. + await search.press("Shift+Tab") + await expect(panel).toHaveCount(0) + + const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) + + await page.keyboard.press(`${modifier}+f`) + await expect(search).toBeFocused() + await expect(page.locator('[data-slot="home-session-search-field"]')).toHaveCSS("outline-style", "solid") + await expect(panel.getByRole("option")).toContainText(earlier.title) }) test("Escape cancels an inline rename whose save does not answer", async ({ page }) => { diff --git a/packages/app/e2e/regression/multi-server.spec.ts b/packages/app/e2e/regression/multi-server.spec.ts index 9903ec224737..f8af6e0f2162 100644 --- a/packages/app/e2e/regression/multi-server.spec.ts +++ b/packages/app/e2e/regression/multi-server.spec.ts @@ -189,34 +189,9 @@ test("a remote session whose server signed the app out asks to sign in again, th await expect(signedOut).toHaveCount(0) }) -// The session route waits this long for an uncached session before it calls the server unreachable. -const RESOLUTION_TIMEOUT_MS = 30_000 - // How often the app checks each server's health. const SERVER_HEALTH_POLL_MS = 10_000 -test("a session its server never answers for says the server is unreachable, then opens", async ({ page }) => { - const late = session({ id: "ses_server_a_late", directory: directoryA, title: "Late session" }) - const sessions = [sessionA] - await setup(page, { tabs: [], a: { sessions } }) - const metadata = await holdRoute(page, new RegExp(`/api/session/${late.id}(\\?|$)`), { method: "GET" }) - await page.clock.install() - await page.goto(sessionHref(late.id)) - await metadata.arrived - const unreachable = page.getByText("Can't reach this server", { exact: true }) - await expect(unreachable).toHaveCount(0) - - await page.clock.fastForward(RESOLUTION_TIMEOUT_MS) - await expect(unreachable).toBeVisible() - await expect(page.getByRole("button", { name: "Close Tab", exact: true })).toBeVisible() - - // The request that hung still fills the cache when it answers. - sessions.push(late) - metadata.release() - await expectSessionTitle(page, late.title) - await expect(unreachable).toHaveCount(0) -}) - // The inbox shows what it has once this long passes, even while a server still has not answered. const INBOX_SETTLE_TIMEOUT_MS = 10_000 diff --git a/packages/app/e2e/regression/new-session.spec.ts b/packages/app/e2e/regression/new-session.spec.ts index 7fd2ccf56e53..c4f0d001b944 100644 --- a/packages/app/e2e/regression/new-session.spec.ts +++ b/packages/app/e2e/regression/new-session.spec.ts @@ -33,6 +33,30 @@ const editor = (page: Page) => page.locator('[data-component="composer-editor"]' const submit = (page: Page) => page.locator('[data-action="composer-submit"]') +test("new-session project picker and provider tip show keyboard focus", async ({ page }) => { + await openDraft(page, { name: "DraftFocus", provider: NO_PROVIDER }) + + const projectPicker = newSessionLocation(page) + + const tip = page.locator('[data-component="new-session-tip"]') + + const connect = tip.getByRole("button", { name: /Connect to 75\+ providers/ }) + + const dismiss = tip.getByRole("button", { name: "Dismiss", exact: true }) + + await newSessionWorktree(page).press("Shift+Tab") + await expect(projectPicker).toBeFocused() + await expect(projectPicker).toHaveCSS("outline-style", "solid") + + await expect(connect).toBeVisible() + await dismiss.press("Shift+Tab") + await expect(connect).toBeFocused() + await expect(connect).toHaveCSS("outline-style", "solid") + await page.keyboard.press("Tab") + await expect(dismiss).toBeFocused() + await expect(dismiss).toHaveCSS("outline-style", "solid") +}) + const tabLink = (page: Page, sessionID: string) => page.locator(`[data-titlebar-tab-link][href="${sessionHref(sessionID)}"]`) @@ -1308,7 +1332,7 @@ test("the location dialog separates added projects from server projects and tags await expect(options.nth(0)).toHaveCSS("height", "32px") await expect(dialog.locator(".palette-menu-search [data-component='text-input-v2']")).toHaveCSS("height", "28px") await expect(dialog.locator(".new-session-location-hints")).toHaveCount(0) - await expect(dialog.locator("..")).toHaveCSS("width", "720px") + await expect(dialog.locator("..")).toHaveCSS("width", "680px") await expect(options.nth(0)).toHaveCSS("display", "flex") await expect(names.nth(0).locator(".command-palette-title")).toHaveCSS("font-size", "13px") await expect(names.nth(0).locator(".command-palette-title")).toHaveCSS("white-space", "nowrap") diff --git a/packages/app/e2e/regression/patch-sticky-header.spec.ts b/packages/app/e2e/regression/patch-sticky-header.spec.ts index e302b5a2217b..cee577749331 100644 --- a/packages/app/e2e/regression/patch-sticky-header.spec.ts +++ b/packages/app/e2e/regression/patch-sticky-header.spec.ts @@ -177,7 +177,7 @@ for (const scenario of scenarios) { const scroller = page.locator('[data-slot="session-timeline-scroll"] .scroll-view__viewport') const toolTitle = scroller.locator('[data-slot="collapsible-trigger"][data-locked]') await expect(toolTitle).toHaveCount(scenario.title ? 1 : 0) - await expect(scroller.locator("[data-session-title]")).toHaveCount(width >= 768 ? 1 : 0) + await expect(page.locator("[data-session-title]")).toHaveCount(width >= 768 ? 1 : 0) for (const file of scenario.files) { const name = new RegExp(`${file}\\.ts`) @@ -218,7 +218,7 @@ for (const scenario of scenarios) { .poll(() => header.evaluate((element) => { const viewport = element.closest(".scroll-view__viewport")! - const title = viewport.querySelector("[data-session-title]")?.firstElementChild + const title = viewport.ownerDocument.querySelector("[data-session-title]")?.firstElementChild const toolTitle = element .closest('[data-component="edit-tool"]') @@ -229,7 +229,7 @@ for (const scenario of scenarios) { .closest('[data-component="collapsed-tool-group"]') ?.querySelector(':scope > [data-component="collapsible"] > [data-slot="collapsible-trigger"]') - const sessionTop = viewport.getBoundingClientRect().top + (title?.getBoundingClientRect().height ?? 0) + const sessionTop = title?.getBoundingClientRect().bottom ?? viewport.getBoundingClientRect().top const top = sessionTop + (group?.getBoundingClientRect().height ?? 0) const rect = element.getBoundingClientRect() const trigger = element.querySelector("button")! diff --git a/packages/app/e2e/regression/review.spec.ts b/packages/app/e2e/regression/review.spec.ts index de8333f93c18..4c4eefe5b1d7 100644 --- a/packages/app/e2e/regression/review.spec.ts +++ b/packages/app/e2e/regression/review.spec.ts @@ -37,6 +37,48 @@ test("review toggle shows its tooltip with the side panel open or closed", async await expect(tooltip).toBeVisible() }) +test("review rings stay visible on the mode trigger, file tree, and diff", async ({ page }) => { + await openSession(page, { + name: "ReviewModeFocus", + vcsDiff: [fileDiff("alpha.ts"), fileDiff("beta.ts")], + }) + await page.getByRole("button", { name: "Toggle review", exact: true }).click() + + const panel = page.getByRole("complementary", { name: "Review and files" }) + + await openReviewLauncher(panel) + + const tree = panel.getByRole("button", { name: "Toggle file tree", exact: true }) + + const mode = panel.getByRole("button", { name: "Git changes", exact: true }) + + await expect(mode).toBeVisible() + await tree.press("Tab") + await expect(mode).toBeFocused() + await expect(mode).toHaveCSS("outline-offset", "-2px") + + const alpha = panel.getByRole("treeitem", { name: "alpha.ts", exact: true }) + + const beta = panel.getByRole("treeitem", { name: "beta.ts", exact: true }) + + await alpha.press("ArrowDown") + await expect(beta).toHaveCSS("outline-style", "solid") + await expect(beta).toHaveCSS("outline-offset", "-2px") + + await tree.click() + await expect(tree).toHaveAttribute("aria-expanded", "false") + await tree.press("Tab") + await expect(mode).toBeFocused() + await expect(mode).toHaveCSS("outline-offset", "-2px") + + const diff = panel.locator('[data-component="file"][data-mode="diff"]') + + await diff.press("Shift+Tab") + await page.keyboard.press("Tab") + await expect(diff).toBeFocused() + await expect.poll(() => diff.evaluate((element) => getComputedStyle(element, "::after").outlineOffset)).toBe("-2px") +}) + for (const view of ["desktop", "mobile"] as const) { test(`offers Git initialization for a project without VCS (${view})`, async ({ page }) => { if (view === "mobile") await page.setViewportSize({ width: 390, height: 844 }) @@ -55,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() @@ -453,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") diff --git a/packages/app/e2e/regression/session-header.spec.ts b/packages/app/e2e/regression/session-header.spec.ts index 68c8fb3b07ee..def9bfb004ee 100644 --- a/packages/app/e2e/regression/session-header.spec.ts +++ b/packages/app/e2e/regression/session-header.spec.ts @@ -43,9 +43,13 @@ for (const direction of ["ltr", "rtl"] as const) { expect(heights).toEqual([28, 28, 28, 28, 28, 28]) + const rename = header.getByRole("heading").getByRole("button", { name: fixture.expected.targetTitle, exact: true }) + for (const editing of [false, true]) { if (editing) { - await header.getByRole("heading").click() + await project.press("Tab") + await expect(rename).toBeFocused() + await page.keyboard.press("Enter") await expect(header.getByRole("textbox")).toHaveValue(fixture.expected.targetTitle) await expect(header.getByRole("textbox")).toBeFocused() } @@ -77,6 +81,13 @@ for (const direction of ["ltr", "rtl"] as const) { await header.getByRole("textbox").press("Escape") await expect(header.getByRole("heading")).toHaveText(fixture.expected.targetTitle) + await expect(rename).toBeFocused() + await page.keyboard.press("Shift+Tab") + await expect(project).toBeFocused() + await details.press("Tab") + await expect(review).toBeFocused() + await page.keyboard.press("Shift+Tab") + await expect(details).toBeFocused() // The header stays one row at every width. for (const width of [900, 1440]) { @@ -254,7 +265,12 @@ test.describe("location", () => { await expect(usageMenu).toBeVisible({ visible: !state.usage }) await expect(header.locator(".session-location-worktree-icon")).toBeVisible() await expect - .poll(() => header.getByRole("heading").evaluate((element) => element.scrollWidth > element.clientWidth)) + .poll(() => + header + .getByRole("heading") + .getByRole("button") + .evaluate((element) => element.scrollWidth > element.clientWidth), + ) .toBe(state.truncated) await expect(header.getByRole("button", { name: "More options", exact: true })).toBeInViewport() await header.getByRole("heading").hover() diff --git a/packages/app/e2e/regression/session-timeline-accessibility.spec.ts b/packages/app/e2e/regression/session-timeline-accessibility.spec.ts index 2375e103b53f..f72acb4309f4 100644 --- a/packages/app/e2e/regression/session-timeline-accessibility.spec.ts +++ b/packages/app/e2e/regression/session-timeline-accessibility.spec.ts @@ -68,6 +68,14 @@ test("jump to latest is reachable only while it is shown", async ({ page }) => { await expect(latest).toBeInViewport() // The click focused the button; hiding it must not leave focus on an invisible control. await expect(jump).not.toBeFocused() + + // From the keyboard, focus continues in the prompt instead of falling to the page. + await page.mouse.wheel(0, -3000) + await expect(latest).not.toBeInViewport() + await jump.focus() + await page.keyboard.press("Enter") + await expect(latest).toBeInViewport() + await expect(page.getByRole("textbox", { name: "Prompt", exact: true })).toBeFocused() }) function lines(count: number) { diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index 1152b0ac027c..83a698d45d64 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -1168,6 +1168,22 @@ test.describe("pages open before slow data", () => { refresh.release() }) + test("extensions keeps the empty MCP panel's keyboard ring inside the tabs", async ({ page }) => { + const { settings } = await open(page) + + await settings.getByRole("tab", { name: "Extensions", exact: true }).click() + + const tab = settings.getByRole("tab", { name: "MCPs", exact: true }) + + const panel = settings.getByRole("tabpanel", { name: "Extensions", exact: true }).getByRole("tabpanel") + + await expect(panel.getByText("Available to all projects")).toBeVisible() + await tab.press("Tab") + await expect(panel).toBeFocused() + await expect(panel).toHaveCSS("outline-style", "solid") + await expect(panel).toHaveCSS("outline-offset", "-2px") + }) + test("extensions", async ({ page }) => { const { settings } = await open(page, { mcp: [{ name: "demo-mcp", status: { status: "connected" } }], @@ -1853,6 +1869,12 @@ test("providers: OpenCode Go connects with its own methods, not the Console sign .click() const dialog = page.getByRole("dialog", { name: "Connect OpenCode Go", exact: true }) await expect(dialog.getByPlaceholder("API key")).toBeVisible() + + const connect = dialog.getByRole("navigation").getByRole("button", { name: "Connect", exact: true }) + + await dialog.getByRole("button", { name: "Close", exact: true }).press("Shift+Tab") + await expect(connect).toBeFocused() + await expect(connect).toHaveCSS("outline-style", "solid") expect(attempts).toEqual([]) }) @@ -2008,8 +2030,8 @@ test("providers: the connect dialog lists connected providers and manages their await expect(dialog.locator('[data-provider-id="linear"]')).toHaveCount(0) await expect(dialog.getByText("MCP", { exact: true })).toHaveCount(0) const container = page.locator('[data-slot="dialog-container"]') - await expect(container).toHaveCSS("width", "480px") - await expect(container).toHaveCSS("max-height", "368px") + await expect(container).toHaveCSS("width", "680px") + await expect(container).toHaveCSS("max-height", "600px") const picker = await container.boundingBox() await openai.click() diff --git a/packages/app/e2e/regression/subagent-child-navigation.spec.ts b/packages/app/e2e/regression/subagent-child-navigation.spec.ts index 001314eb8793..2f168124f69e 100644 --- a/packages/app/e2e/regression/subagent-child-navigation.spec.ts +++ b/packages/app/e2e/regression/subagent-child-navigation.spec.ts @@ -435,7 +435,11 @@ function titleInlineStart(title: Locator) { return title.evaluate((element) => { const range = document.createRange() - range.selectNodeContents(element) + const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT) + const text = walker.nextNode() + + if (!text) return 0 + range.selectNodeContents(text) const bounds = range.getBoundingClientRect() diff --git a/packages/app/e2e/regression/timeline-geometry.spec.ts b/packages/app/e2e/regression/timeline-geometry.spec.ts index f87b30f755a3..f1ae1869225e 100644 --- a/packages/app/e2e/regression/timeline-geometry.spec.ts +++ b/packages/app/e2e/regression/timeline-geometry.spec.ts @@ -340,7 +340,7 @@ for (const outline of [ }, ) - // A second turn adds the fixed turn gap, which must not get the paint-rounding margin. + // A second turn adds the fixed turn gap, which must not get the paint margin the other rows keep. await setupTimeline(page, { messages: [ userMessage(undefined, { @@ -376,7 +376,7 @@ for (const outline of [ })), ) - expect(rows.filter((row) => row.tag !== "TurnGap").every((row) => row.clipMargin === "0.5px")).toBe(true) + expect(rows.filter((row) => row.tag !== "TurnGap").every((row) => row.clipMargin === "5px")).toBe(true) expect(rows.filter((row) => row.tag === "TurnGap")).toEqual([{ tag: "TurnGap", clipMargin: "0px" }]) const part = page.locator(`[data-timeline-part-id="${partID}"]`) diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 324ede83bce9..89e671161c5f 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -1483,22 +1483,19 @@ test.describe("background work", () => { const title = header.getByRole("heading") const before = await title.boundingBox() - const exit = await pauseExitAnimations(working) + const exit = await seekExit(working, 100) await timeline.transport.send(status("idle", 1, childID)) - await expect.poll(() => exit.evaluate((animations) => animations.length)).toBeGreaterThan(0) - await exit.evaluate((animations) => animations.forEach((animation) => (animation.currentTime = 100))) - await expect(working).toBeAttached() - const midway = await title.boundingBox() + const midway = await exit.evaluate((state) => state.sibling) - expect(midway!.x).toBeLessThan(before!.x) - await exit.evaluate((animations) => animations.forEach((animation) => animation.finish())) + expect(midway).toBeLessThan(before!.x) + await exit.evaluate((state) => state.animations.forEach((animation) => animation.finish())) await expect(working).toHaveCount(0) const after = await title.boundingBox() - expect(after!.x).toBeLessThan(midway!.x) + expect(after!.x).toBeLessThan(midway) expect(after!.x).toBeCloseTo(before!.x - 24, 0) await exit.dispose() await header.locator('[data-slot="session-title-parent"]').click() @@ -3322,22 +3319,29 @@ test("reaches the quote action from the keyboard and blocks a selection over the await page.mouse.up() }) -function pauseExitAnimations(locator: Locator) { - return locator.evaluateHandle((element) => { +// Presence unmounts an element once its exit's duration has passed, even while the exit is paused, so a paused exit +// cannot be held across test round trips. Seek and measure the next sibling in the task that starts the exit instead. +function seekExit(locator: Locator, ms: number) { + return locator.evaluateHandle((element, ms) => { const animations: Animation[] = [] - const pause = (event: AnimationEvent) => { - if (event.target !== element || event.animationName !== "exit") return - - animations.push(...element.getAnimations()) - animations.forEach((animation) => animation.pause()) - element.removeEventListener("animationstart", pause) - } + const sibling = new Promise((resolve) => { + const observer = new MutationObserver(() => { + if (element.getAttribute("data-visible") !== "false") return + observer.disconnect() + animations.push(...element.getAnimations()) + animations.forEach((animation) => { + animation.pause() + animation.currentTime = ms + }) + resolve(element.nextElementSibling!.getBoundingClientRect().x) + }) - element.addEventListener("animationstart", pause) + observer.observe(element, { attributes: true, attributeFilter: ["data-visible"] }) + }) - return animations - }) + return { animations, sibling } + }, ms) } function notes(label: string, count: number) { diff --git a/packages/app/e2e/utils/mock-api.ts b/packages/app/e2e/utils/mock-api.ts index 914ed5c61f7f..545f62d94a26 100644 --- a/packages/app/e2e/utils/mock-api.ts +++ b/packages/app/e2e/utils/mock-api.ts @@ -235,6 +235,7 @@ const Group = HttpApiGroup.make("mock") ) .add(HttpApiEndpoint.get("websearchProviders", "/api/websearch/provider", { success: Json })) .add(HttpApiEndpoint.get("usageLimits", "/api/experimental/usage/limits", { success: Json })) + .add(HttpApiEndpoint.get("jobList", "/api/experimental/job", { success: Json })) .add( HttpApiEndpoint.get("worktreeList", "/api/worktree", { query: Schema.Struct({ projectID: Schema.String }), diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index 6b06efc02d00..3794d30fb1a2 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -947,6 +947,8 @@ function mockHandlers( Effect.sync(() => ({ location: location(config), data: resolve(config.websearchProviders ?? []) })), // No scenario signs in to an OpenCode Console workspace, so none has usage limits. usageLimits: () => Effect.succeed({ location: location(config), data: null }), + // No scenario runs background jobs (Code Mode scripts or subagent work), so none is running. + jobList: () => Effect.succeed({ data: [] }), worktreeList: () => Effect.sync(() => { if (config.worktrees) return resolve(config.worktrees) diff --git a/packages/app/index.html b/packages/app/index.html index 1cec152cd0e9..c9c930acf6d6 100644 --- a/packages/app/index.html +++ b/packages/app/index.html @@ -10,13 +10,13 @@ OpenCode - + - + 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, diff --git a/packages/app/perf/send.bench.ts b/packages/app/perf/send.bench.ts new file mode 100644 index 000000000000..c828da4100e7 --- /dev/null +++ b/packages/app/perf/send.bench.ts @@ -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((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() + }, + }, + }, +}) diff --git a/packages/app/src/app.tsx b/packages/app/src/app.tsx index 78083534acfa..369ec173acec 100644 --- a/packages/app/src/app.tsx +++ b/packages/app/src/app.tsx @@ -3,12 +3,21 @@ import { VoiceProvider } from "@/voice/context" import { VoiceOverlay } from "@/voice/composer" import { DialogProvider } from "@opencode/ui/context/dialog" import { FileComponentProvider } from "@opencode/ui/context/file" +import { installFocusRescue } from "@opencode/ui/context/focus-rescue" import { Font } from "@opencode/ui/font" import { ThemeProvider } from "@opencode/ui/theme/context" import { MetaProvider, Title } from "@solidjs/meta" import { type BaseRouterProps, Router } from "@solidjs/router" import { QueryClient, QueryClientProvider } from "@tanstack/solid-query" -import { type Component, createRenderEffect, ErrorBoundary, type JSX, type ParentProps } from "solid-js" +import { + type Component, + createRenderEffect, + ErrorBoundary, + type JSX, + onCleanup, + onMount, + type ParentProps, +} from "solid-js" import { Dynamic } from "solid-js/web" import { CommandProvider } from "@/shell/commands/command" import { DesktopCommands } from "@/shell/commands/desktop" @@ -21,6 +30,7 @@ import { TabsProvider } from "@/shell/tabs/tabs" import { ErrorPage } from "@/shell/errors/error" import { AppRoutes, File, preloadRoute } from "@/shell/routes/routes" import { PluginRoot } from "@/runtime/plugin/root" +import { baseRouter } from "@/runtime/platform/base-path-router" export { preloadRoute } @@ -55,6 +65,8 @@ export function AppBaseProviders( onThemeApplied?: (mode: "light" | "dark", scheme: "system" | "light" | "dark") => void }>, ) { + onMount(() => onCleanup(installFocusRescue())) + return ( OpenCode @@ -114,7 +126,7 @@ export function AppInterface(props: { return ( - + diff --git a/packages/app/src/components-lab/focus-rings.stories.tsx b/packages/app/src/components-lab/focus-rings.stories.tsx index 2e604d9e0f97..13a4747b1d66 100644 --- a/packages/app/src/components-lab/focus-rings.stories.tsx +++ b/packages/app/src/components-lab/focus-rings.stories.tsx @@ -19,6 +19,7 @@ import { Icon } from "@opencode/ui/icon" import { IconButton } from "@opencode/ui/icon-button" import { InlineInput } from "@opencode/ui/inline-input" import { LineComment, LineCommentOverflowIcon } from "@opencode/ui/line-comment" +import { ProjectAvatar } from "@opencode/ui/project-avatar" import { RadioGroup, RadioItem } from "@opencode/ui/radio" import { SegmentedControl, SegmentedControlItem } from "@opencode/ui/segmented-control" import { Select } from "@opencode/ui/select" @@ -27,7 +28,7 @@ import { Switch } from "@opencode/ui/switch" import { Tabs } from "@opencode/ui/tabs" import { TextInput } from "@opencode/ui/text-input" import { Textarea } from "@opencode/ui/textarea" -import { createEffect, For, onCleanup, type JSX } from "solid-js" +import { createEffect, For, onCleanup, Show, type JSX } from "solid-js" import { focusTarget, forceFocusStyles } from "./force-focus" type Specimen = { @@ -36,9 +37,11 @@ type Specimen = { render: () => JSX.Element // The element that would hold focus. Defaults to the first focusable element in the specimen. target?: string + // What changed to bring it in line with the focus decisions (design review, 18 Nov). + note?: string } -type Group = { name: string; css: string; specimens: Specimen[] } +type Group = { name: string; css: string; note?: string; specimens: Specimen[] } const schemes = ["lab", "light", "dark"] as const @@ -61,8 +64,9 @@ const iconButtonVariants = ["neutral", "contrast", "submit", "ghost", "ghost-mut const groups: Group[] = [ { - name: "Outline 2px, offset 2.5px", - css: "outline: 2px solid var(--v2-border-border-focus); outline-offset: 2.5px", + name: "Outline 2px, offset 2px (default)", + css: "outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px", + note: "The default for every control with room around it. Keyboard and screen reader focus only (:focus-visible), never a mouse click. Offsets were 2.5px, 2px and 1px; 2.5px became 2px, which also stays crisp at 1x.", specimens: [ ...buttonVariants.map((variant) => ({ name: `Button ${variant}`, @@ -74,6 +78,61 @@ const groups: Group[] = [ source: "ui/src/actions/icon-button/icon-button.css", render: () => } aria-label="Add" />, })), + { + name: "Timeline jump to latest", + source: "app/src/session/timeline/virtualizer.tsx", + note: "A Tab stop while it shows, the only quick way back down a long timeline from the keyboard. Its container is inert while it's hidden.", + render: () => ( + + ), + }, + { + name: "Button loading", + source: "ui/src/actions/button/button.css", + note: "Keeps the ring while it keeps focus. aria-busy and its loading text say it is working.", + render: () => , + }, + { + name: "New session project selector", + source: "app/src/new-session/view.tsx", + render: () => ( + + ), + }, + { + name: "Session header project", + source: "app/src/session/session-identity-header.tsx", + note: "Was background only. Keyboard focus now uses the default ring; the background still indicates hover and an open menu.", + render: () => ( + + ), + }, + { + name: "Editable session title", + source: "app/src/session/timeline/message-timeline.tsx", + note: "Was a clickable heading outside the tab order. The heading now contains a native button with the default ring.", + render: () => ( +

+ +

+ ), + }, { name: "Composer lane pill", source: "app/src/session/composer/composer-lane.css", @@ -83,12 +142,115 @@ const groups: Group[] = [ ), }, - ], - }, - { - name: "Outline 2px, offset 2px", - css: "outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px", - specimens: [ + { + name: "Checkbox standard (legacy)", + source: "ui/src/forms/checkbox/checkbox.css", + note: "Was a box-shadow ring (--shadow-xs-border-focus) with a blue border. Now the default outline.", + render: () => Standard checkbox, + }, + { + name: "Switch standard (legacy)", + source: "ui/src/forms/switch/switch.css", + note: "Was a box-shadow ring (--shadow-xs-border-focus) with a blue border. Now the default outline.", + render: () => ( + + Standard switch + + ), + }, + { + name: "Project colour swatch", + source: "app/src/settings/workspaces/project.css", + note: "Was a blue box-shadow ring shared with selection. Focus is now the default outline and selection a neutral ring.", + render: () => ( + + ), + }, + { + name: "Session compaction toggle", + source: "session-ui/src/components/session-compaction.css", + note: "Was 1px in --v2-text-text-accent at a 2px offset.", + render: () => ( +
+ +
+ ), + }, + { + name: "Markdown session link", + source: "session-ui/src/components/markdown.css", + note: "Was 2px currentColor at a 2px offset.", + render: () => ( + + Session link + + ), + }, + { + name: "Prompt link", + source: "session-ui/src/components/message-part.css", + note: "Had no authored rule, so it showed the browser default ring.", + render: () => ( + + ), + }, + { + name: "External link, and anything else without its own rule", + source: "ui/src/styles/base.css", + note: "Showed the browser's ring, in the system accent colour (orange with an orange macOS accent). base.css now makes the shared ring the default for every :focus-visible element, and gives links the 4px radius the other rings have.", + render: () => ( + + Help & feedback + + + ), + }, + { + name: "Collapsible trigger", + source: "ui/src/components/collapsible.css", + note: "Was background only, like a list row, though it is a standalone disclosure (Settings › Timeline › Advanced). Now the default ring, with a 4px radius. The new timeline's tool rows ring their line of text instead (timeline-next.css).", + render: () => ( + + + Advanced + + + Content + + ), + }, + { + name: "Select inline", + source: "ui/src/forms/select/select.css", + note: "Had no ring: inline appearance removes the outline that focus recolours. Now the default outline.", + render: () => undefined} + /> + } + /> + } + /> + + ), + }, { name: "Tab strip: End puts the last tab under the sticky Add tab", failure: "Occluded", @@ -161,175 +869,1158 @@ const surfaces: Surface[] = [ sizing: "Side panel 360px wide with 13 tabs open.", source: "app/src/runtime/plugin/side-region.tsx:333 (sticky +), ui tabs.css:605–621 (strip mask), tabs.css:100 (no ring)", + fix: 'Kobalte moved focus without scrolling, so End left the tab where it was. The strip now scrolls a keyboard-focused tab into view (tab-strip-scroll.ts), and its scroll-padding-inline, --tab-strip-add plus the 24px fade (tabs.css), keeps it clear of the "+". The ring covers the whole tab, close button included.', from: { scroller: '[data-slot="tabs-list"]', edge: "start" }, render: () => , }, { - name: "Selected panel tab: no visible focus", - failure: "Invisible", - target: '[data-pane-tab="changes"]', - keys: "From any tab, press Home.", - sizing: "Any panel width.", - source: "ui/src/navigation/tabs/tabs.css:100–103 (outline: none, box-shadow: none)", - from: { scroller: '[data-slot="tabs-list"]', edge: "end" }, - render: () => , + name: "Selected panel tab: no visible focus", + failure: "Invisible", + target: '[data-pane-tab="changes"]', + keys: "From any tab, press Home.", + sizing: "Any panel width.", + source: "ui/src/navigation/tabs/tabs.css:100–103 (outline: none, box-shadow: none)", + fix: "The tab draws the 2px ring inset (offset -2px) around its label and close button, since the strip scrolls and would clip a ring outside.", + from: { scroller: '[data-slot="tabs-list"]', edge: "end" }, + render: () => , + }, + ], + also: [ + "Review header at a 164px preview: Previous and Next overlap the line buttons, and Split diff is cut off.", + "CSV preview at 80px: Copy content overflows the header.", + "Line comment More options runs past the panel edge at 360px.", + ], + }, + { + name: "Settings", + cases: [ + { + name: "Interface layout: selection and focus use the same blue", + failure: "Inconsistent", + target: "input", + keys: "Tab onto the selected Interface layout card.", + sizing: "The card has a separate selected border and an outset focus ring.", + source: "app/src/settings/general/interface-mode.css", + fix: "Selection is a 2px neutral border, a check outside the corner and a faded sketch on the other cards. Blue is only the keyboard ring.", + render: () => , + }, + ...(["Work account", "Add account"] as const).map( + (label): Case => ({ + name: `Connect: ${label} has only a background change`, + failure: "Inconsistent", + target: "button", + keys: "Open a provider with saved accounts in Connect and Tab through the accounts and Add account.", + sizing: "Each button is a separate Tab stop in the scrolling dialog.", + source: "app/src/providers/connect/dialog.tsx", + fix: "Show a shared inset ring, rather than reusing the hover background as the only cue.", + render: () => ( + + ), + }), + ), + { + name: "Extensions tab panel: the ring loses both sides", + failure: "Clipped", + target: '[role="tabpanel"]', + keys: "Open Settings › Extensions › MCPs and Tab from the selected tab onto its panel.", + sizing: "The panel stretches edge to edge inside a clipping tabs root.", + source: "app/src/settings/settings.css (.settings-subtabs)", + fix: "Keep the tab panel reachable, including when it has no interactive content. Draw its ring inset, independently of the rings on its children.", + render: () => ( +
+ + + MCPs + Plugins + + +
+ Available to all projects + Manage in opencode.json +
+
+ Manage plugins +
+
+ ), + }, + { + name: "Connect provider dialog: breadcrumb focus only changes text colour", + failure: "Inconsistent", + target: "nav button", + keys: "Open Connect, choose a provider, then Tab or Shift+Tab to the Connect breadcrumb.", + sizing: "The breadcrumb is a compact text button, not a full-width row.", + source: "app/src/providers/connect/dialog.tsx", + fix: "Both interactive breadcrumbs use the shared outset keyboard ring with a 4px radius. Non-interactive breadcrumb labels remain plain text.", + render: () => ( +
+ +
+ ), + }, + { + name: "Providers: Show more providers draws a full-width square ring", + failure: "Inconsistent", + target: ".settings-providers-view-all", + keys: "In Settings › Providers, Tab from the last Connect button to Show more providers.", + sizing: "The section is a column; by default its children stretch across the panel.", + source: "app/src/settings/settings.css (.settings-providers-view-all)", + fix: "Size the text action to its label, give it a 4px corner radius, and use the shared 2px outset ring.", + render: () => ( +
+

Popular providers

+ + + + + + +
+ ), + }, + { + name: "Models: Shift+Tab hides the focused switch under the sticky header", + failure: "Occluded", + target: '[data-component="settings-row"]:nth-child(5) [data-slot="switch-input"]', + keys: "Click the last row's name, then press Shift+Tab until a row scrolls up.", + sizing: "Audited at 1280×800 and 390×680. The panel has no scroll padding for its sticky header.", + source: "app/src/settings/settings.css:587–611 (.settings-panel, sticky .settings-tab-header)", + fix: "tab-header.ts writes the header's height to --settings-tab-header-height; focusable controls in .settings-tab-body take it, plus the 24px fade, as their top scroll-margin.", + from: { scroller: ".settings-panel", edge: "end" }, + render: () => , + }, + { + name: "Extensions: Check for updates and How to add skills cut at the right", + failure: "Clipped", + target: ".settings-extension-link", + keys: "Open Extensions › Skills (or Plugins), press Tab until the link (or Check for updates) is focused.", + sizing: "Any width. Both sit flush with the sub-tab panel's end edge.", + source: + "ui tabs-current.css (tabs-v2 root overflow: clip), settings.css (.settings-subtabs panel overflow: auto), extensions.tsx", + fix: "The tabs root clips with a 5px overflow-clip-margin, and the scrolling sub-tab panel pads its sides by 5px and takes it back with a negative margin, so a ring at either edge shows.", + render: () => ( +
+ + + Skills + + +
+ Available to all projects + + How to add skills + +
+
+
+
+ ), + }, + { + name: "Worktrees: Delete ring cut at the top and right by its row", + failure: "Clipped", + target: '[aria-label="Delete “opencode-dialogs”?"]', + keys: "Click the path, press Tab.", + sizing: "Audited at 1280×800. Delete is the row's top-right control.", + source: "app/src/settings/settings.css:1919–27 (row overflow: hidden), workspaces.tsx:543–553", + fix: "The row clips with overflow: clip and a 5px overflow-clip-margin instead of overflow: hidden, so the removal animation still clips and the ring shows.", + render: () => ( +
+
+ +
+
+
+
+
/Users/alex/work/opencode-dialogs
+ 0 sessions in opencode +
+
+ } + /> +
+
+
+
+
+
+
+ ), + }, + { + name: "Language: inline select shows no focus", + failure: "Invisible", + target: '[data-component="select-v2"]', + keys: "Click the row title, press Tab.", + sizing: "Any width. Inline appearance sets outline: none, and focus only recolours that outline.", + source: "ui/src/forms/select/select.css:100–103, 193–204", + fix: "Inline Select draws the default ring immediately on keyboard focus, with no outline at rest. A transparent rest outline would show in forced colours. Bordered selects keep their normal field border.", + render: () => ( +
+ + + undefined} /> + ), + }, + { + name: "Context menu: Escape after a right-click rings the row", + failure: "Inconsistent", + target: "button", + keys: "Right-click the row, then press Escape: no ring.", + sizing: "Any context menu: titlebar tabs, Home sessions and projects, file trees.", + source: "ui/src/navigation/menu/menu.tsx (Menu.Context)", + fix: "Context menus returned focus through Kobalte alone. They now record how they opened, as dropdown menus do, and return focus to what had it with that ring.", + render: () => ( + + + + + + + Rename + Archive + + + + ), + }, + { + name: "Home project picker: no keyboard ring, then a ring after Escape", + failure: "Invisible", + target: '[data-component="home-projects-dropdown"]', + keys: "On a narrow Home, Tab to the project picker. Click it and press Escape: no ring.", + sizing: "Below the Home breakpoint, the picker replaces the projects panel and fills its column.", + source: "app/src/home/projects/view.tsx", + fix: "The trigger suppressed its outline, so it never showed focus. It now takes the shared ring inset (-2px), and the popover restores it with createOverlayFocus, as Select does.", + render: () => , + }, + { + name: "Composer todo and plugin pills: Escape after a click rings the pill", + failure: "Inconsistent", + target: '[data-component="session-todo-pill"]', + keys: "Click the todo pill, press Escape: no ring. Tab to it, press Enter, then Escape: the ring returns.", + sizing: "The pills in the lane above the composer.", + source: "app/src/session/composer/todo-pill.tsx, plugin-pills.tsx", + fix: "Both popovers restore their pill with createOverlayFocus instead of Kobalte's plain focus().", + render: () => , + }, + ], + also: [ + "Reviewed, left as is: the Home browse dialog's fallback focus (home/projects/browse.tsx) runs only when the opener has gone; the mobile panel drawer's Back and the location picker's Choose return follow the key or click that closed them.", + "The workspace selector (new-session/workspace/selector.tsx) returns focus to the composer, whose field ring follows field-focus.tsx.", + ], + }, + { + name: "Provider dialogs", + cases: [ + { + name: "Connect provider list: Tab and arrow keys only change the background", + failure: "Inconsistent", + target: "[data-provider-id]", + keys: "Open Connect, then press ArrowDown in the search field, or Tab into the list.", + sizing: "Full-width rows in a scroller with no side padding.", + source: "app/src/providers/connect/dialog.tsx (ProviderList)", + fix: "The rows picked their background on :focus, so a click drew it too, and drew no ring. They now take the shared ring inset (-2px) on :focus-visible; hover and the arrow-key highlight keep the background.", + render: () => ( +
+ + {(name) => ( + + )} + +
+ ), + }, + { + name: "Sign-in method: keyboard focus only changes the background", + failure: "Inconsistent", + target: '[data-action="provider-connect-method"]', + keys: "Open Connect, choose a provider with more than one sign-in method, then Tab to a method.", + sizing: "Full-width rows.", + source: "app/src/providers/connect/dialog.tsx (MethodSelection)", + fix: "The shared ring inset (-2px) replaces the background. The chevron still appears on hover and keyboard focus.", + render: () => ( +
+ + {(label) => ( + + )} + +
+ ), + }, + { + name: "Paste the redirect URL: focus only underlines the toggle", + failure: "Inconsistent", + target: "button[aria-expanded]", + keys: "Start a browser sign-in, then Tab to the paste toggle under the waiting button.", + sizing: "The toggle stretches across the step, between its top and bottom borders.", + source: "app/src/providers/connect/dialog.tsx (OAuth paste)", + fix: "The underline is gone. The toggle takes a 6px radius and the shared ring inset (-2px), inside the borders.", + render: () => ( +
+ +
+ ), + }, + { + name: "Remote server label: focus only changes the text colour", + failure: "Inconsistent", + target: '[tabindex="0"]', + keys: "Connect a provider on a remote server, then Tab to the server label in the dialog header.", + sizing: "A compact label that opens a tooltip.", + source: "app/src/providers/connect/dialog.tsx (DialogHeader)", + fix: "The label uses the shared 2px outset ring with its 4px radius; the text colour no longer changes.", + render: () => ( +
+ + + On devbox + +
+ ), + }, + { + name: "First models after connecting: keyboard focus only changes the background", + failure: "Inconsistent", + target: ".connected-model-row", + keys: "Connect a provider for the first time, then Tab to a model.", + sizing: "Full-width radio rows in a list that clips them.", + source: "app/src/providers/connect/dialog.tsx (ConnectionModelList), models.css", + fix: "The row draws the shared ring inset (-2px) instead of the hover background, inside the list's clip. A checked row keeps its check, so selection stays distinct.", + render: () => ( +
+ + + {(name, index) => ( +
+ +
+ )} +
+
+
+ ), + }, + { + name: "Choose a model, no paid provider: rows and cards only change the background", + failure: "Inconsistent", + target: "[data-provider-id]", + keys: "Without a paid provider, open the model picker, then Tab or press ArrowDown.", + sizing: "Full-width model rows, two-column provider cards and a full-width View more row.", + source: "app/src/providers/models/unpaid.tsx", + fix: "All three picked a background on :focus, so a click drew it too. Rows and View more take the shared ring inset (-2px); the cards have room, so they take it outset (2px). Hover keeps the background.", + render: () => ( +
+ +
+ + {(name) => ( + + )} + + +
+
+ ), + }, + ], + also: [], + }, + { + name: "Shared controls", + cases: [ + { + name: "Error details: thin focus outline", + failure: "Inconsistent", + target: "pre", + keys: "Tab into the selectable details on an error.", + sizing: "The details fill a scrollable area.", + source: "ui/src/components/error-details.css", + fix: "Use the same inset 2px ring as other scrollable regions.", + render: () => ( + + + + ), + }, + ...(["palette-menu-row", "search-list-row"] as const).map( + (row): Case => ({ + name: `${row === "palette-menu-row" ? "Palette" : "Search list"}: active option loses contrast in forced colours`, + failure: "Invisible", + target: "input", + keys: "Enable forced colours and use the arrow keys while focus stays in the search input.", + sizing: "Applies to active options rather than independent Tab stops.", + source: `app/src/shell/${row === "palette-menu-row" ? "palette-menu" : "search-list"}.css`, + fix: "Use system Highlight and HighlightText colours for the active option.", + render: () => , + }), + ), + { + name: "Focus ring colour: the default did not adapt to the scheme", + failure: "Inconsistent", + target: "button", + keys: "Switch Scheme between Light and Dark. With forced focus off, Tab to the button in each scheme.", + sizing: "The ring keeps the same width and offset in both schemes.", + source: "ui/src/styles/tokens/theme.css, ui/src/theme/v2/mapping.ts", + fix: "Use Blue 500 in light mode and Blue 400 in dark mode. The Settings colour experiment is no longer needed.", + render: () => , + }, + { + name: "Links: the browser's orange, square ring", + failure: "Inconsistent", + target: "a", + keys: "Tab to any link without its own focus rule, such as Help & feedback.", + sizing: "Any width. The colour is the system accent, orange with an orange macOS accent.", + source: "ui/src/styles/base.css", + fix: "base.css makes the shared ring the default for every :focus-visible element, so nothing falls back to the browser's, and gives links a 4px radius like the other rings.", + render: () => ( + + Help & feedback + + + ), + }, + { + name: "Switch: a black ring flashes as focus arrives", + failure: "Inconsistent", + target: '[data-slot="switch-input"]', + keys: "Tab onto a switch and watch the ring appear.", + sizing: "Any width. Tab with forced colours enabled to check that the unfocused switch has no ring.", + source: "ui/src/forms/switch/switch.css", + fix: "Draw the full ring immediately on keyboard focus, with no outline at rest. In forced colours, a system-colour border keeps the track and thumb visible.", + render: () => Compact switch, + }, + { + name: "Radio: forced colours show a ring before focus", + failure: "Inconsistent", + target: '[data-slot="radio-v2-item-input"]', + keys: "Tab to the selected radio, then use an arrow key to move to the next radio.", + sizing: + "Reproduces in Chromium with forced colours enabled. The regular radio border is separate from its ring.", + source: "ui/src/forms/radio/radio.css", + fix: "Remove the transparent rest outline and show the focus ring immediately. A system-colour border and selected dot keep the radio visible in forced colours.", + render: () => ( + + + + + ), + }, + { + name: "Standard checkbox and switch: blue border and soft shadow", + failure: "Inconsistent", + target: '[data-slot="checkbox-checkbox-input"]', + keys: "Tab onto a standard (legacy) checkbox or switch.", + sizing: "Any width.", + source: "ui/src/forms/checkbox/checkbox.css, switch/switch.css", + fix: "Was a blue border with the --shadow-xs-border-focus box-shadow. Now the shared 2px outline at a 2px offset.", + render: () => Standard checkbox, }, - ], - also: [ - "Review header at a 164px preview: Previous and Next overlap the line buttons, and Split diff is cut off.", - "CSV preview at 80px: Copy content overflows the header.", - "Line comment More options runs past the panel edge at 360px.", - "Files and Review trees: ArrowDown from the selected file moves focus with no visible change (pierre-tree.tsx:41–42, 84–92).", - "Git changes inline select, and the source and diff viewers: no visible focus (same pattern as the Language select below).", - ], - }, - { - name: "Settings", - cases: [ { - name: "Models: Shift+Tab hides the focused switch under the sticky header", - failure: "Occluded", - target: '[data-component="settings-row"]:nth-child(5) [data-slot="switch-input"]', - keys: "Click the last row's name, then press Shift+Tab until a row scrolls up.", - sizing: "Audited at 1280×800 and 390×680. The panel has no scroll padding for its sticky header.", - source: "app/src/settings/settings.css:587–611 (.settings-panel, sticky .settings-tab-header)", - from: { scroller: ".settings-panel", edge: "end" }, + name: "Segmented control: ring runs into the next item", + failure: "Clipped", + target: '[data-slot="segmented-control-v2-item"]', + keys: "Tab onto a segmented control.", + sizing: "Any width. Items sit edge to edge in a 28px track.", + source: "ui/src/navigation/segmented-control/segmented-control.css", + fix: "Was 2px at a 1px offset, over the neighbouring item and the track. Now inset (-2px), inside the item.", render: () => ( -
-
-
-
-

Models

- - Choose which models appear in the model picker. - -
-
- undefined} /> -
-
- - - {(name) => ( - -
- - {name} - -
-
- )} -
-
-
-
+ + One + Two + ), }, { - name: "Worktrees: Delete ring cut at the top and right by its row", + name: "Text field clear button: ring runs past the field's edge", failure: "Clipped", - target: '[aria-label="Delete “opencode-dialogs”?"]', - keys: "Click the path, press Tab.", - sizing: "Audited at 1280×800. Delete is the row's top-right control.", - source: "app/src/settings/settings.css:1919–27 (row overflow: hidden), workspaces.tsx:543–553", + target: '[data-slot="text-input-v2-icon-button"]', + keys: "Type in a clearable field, press Tab to the clear button.", + sizing: "Any width. The button sits at the field's end.", + source: "ui/src/forms/text-input/text-input.css", + fix: "Was 2px at a 1px offset, over the field's border. Now inset (-2px), inside the button.", render: () => ( -
-
- -
-
-
-
-
/Users/alex/work/opencode-dialogs
- 0 sessions in opencode -
-
- } - /> -
-
-
-
-
-
+
+
), }, { - name: "Language: inline select shows no focus", + name: "Busy button: the ring disappears while it works", failure: "Invisible", - target: '[data-component="select-v2"]', - keys: "Click the row title, press Tab.", - sizing: "Any width. Inline appearance sets outline: none, and focus only recolours that outline.", - source: "ui/src/forms/select/select.css:100–103, 193–204", + target: '[data-component="button-v2"]', + keys: "Start a provider sign-in that waits for the browser, then Tab to the waiting button.", + sizing: "Any Button with the loading variant that keeps focus.", + source: "ui/src/actions/button/button.css, button.tsx, app/src/providers/connect/step-actions.tsx", + fix: "The loading variant no longer drops the ring. The ring alone can't say whether the button works, so Button also sets aria-busy for it, and the spinner and its text show the wait.", + render: () => Waiting for the browser…, + }, + { + name: "Accordion rows: the next row covers the bottom of the ring", + failure: "Clipped", + target: '[data-slot="accordion-trigger"]', + keys: "Open the Context tab in the right panel and Tab through Raw messages.", + sizing: "Rows overlap by 1px so their borders merge, and each sticky header has the same z-index.", + source: "ui/src/data-display/accordion/accordion.css, ui/src/components/sticky-accordion-header.css", + fix: "The header holding the focused trigger is raised above its neighbours, so the whole inset ring shows. Sticky headers rise above the other sticky headers.", render: () => ( -
- - - { + if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return + + event.preventDefault() + setActive((index) => 1 - index) + }} + /> +
+ + {(label, index) => ( + + )} + +
+
+ ) +} + +function TreeFocusExample() { + return ( +
{ + const root = host.attachShadow({ mode: "open" }) + + const style = document.createElement("style") + + style.textContent = ` + ${treeFocusCss} + ${treeFocusCss.replaceAll(":focus-visible", "[data-lab-focus]")} + button { display: block; width: 100%; height: 28px; border: 0; border-radius: 4px; + background: transparent; color: inherit; text-align: start; padding-inline: 8px; font: inherit; } + button[aria-selected="true"] { background: var(--v2-overlay-simple-overlay-pressed); } + ` + root.append(style) + + const rows = ["README.md", "index.ts"].map((name, index) => { + const row = document.createElement("button") + + row.dataset.type = "item" + row.dataset.itemFocused = String(index === 0) + row.setAttribute("role", "treeitem") + row.setAttribute("aria-selected", String(index === 0)) + row.tabIndex = -1 + row.textContent = name + root.append(row) + + return row + }) + + host.onkeydown = (event) => { + if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return + + event.preventDefault() + rows.forEach((row, index) => (row.dataset.itemFocused = String(index === (event.key === "ArrowUp" ? 0 : 1)))) + } + }} + /> + ) +} + +function HomeSearchFocusExample(props: { forced: boolean }) { + const focus = createPreviewFieldFocus(() => props.forced) + + return ( +
+ + +
+ ) +} + +function ComposerFocusExample(props: { forced: boolean }) { + const focus = createPreviewFieldFocus(() => props.forced) + + return ( +
+ +
+
+
focus.enter(event.currentTarget)} + onBlur={focus.leave} + > + Ask anything +
+
+
+ } aria-label="Attach" /> +
+
+
+ ) +} + +// The Models page, with its header measured the way Settings measures it. +function ModelsPanel() { + let panel: HTMLDivElement | undefined + + onMount(() => { + const header = panel?.querySelector(".settings-tab-header") + + if (panel && header) onCleanup(trackTabHeader(panel, header)) + }) + + return ( +
+
+
+
+

Models

+ Choose which models appear in the model picker. +
+
+ undefined} /> +
+
+ + + {(name) => ( + +
+ + {name} + +
+
+ )} +
+
+
+
+ ) +} + function TabStrip() { return (
+ {/* The panel actions slot, here only the space side-region.tsx keeps for the panel toggle. */} +
+
+
@@ -580,3 +2507,289 @@ export default { } export const AllSurfaces = { render: (args: VisibilityArgs) => } + +// The popover wiring the Home project picker and the composer pills share. +function OverlayPopover(props: { component: string; label: string; width?: string }) { + const overlayFocus = createOverlayFocus() + + let trigger: HTMLButtonElement | undefined + + return ( + + + {props.label} + + + + overlayFocus.restore(event, trigger)} + > + Popover content + + + + ) +} + +function RemovalTabs() { + const [tabs, setTabs] = createSignal(["Refactor store", "Draft", "Fix tests", "Release notes"]) + + return ( +
+
+ + {(tab) => ( +
+ event.preventDefault()}> + {tab} + + } + aria-label={`Close ${tab}`} + onClick={() => setTabs((list) => list.filter((item) => item !== tab))} + /> +
+ )} +
+
+ +
+ ) +} + +function RemovalSettingsRows() { + const dialog = useDialog() + + const initial = ["main", "focus-rings", "session-store"] + + const [rows, setRows] = createSignal(initial) + + const confirm = (name: string) => + dialog.show(() => ( + + + Delete {name}? + + The worktree and its changes are removed. + + + + + + )) + + return ( +
+ + + {(name) => ( + + + + )} + + + +
+ ) +} + +function RemovalChips() { + const initial = ["notes.md", "store.ts", "plan.md"] + + const [chips, setChips] = createSignal(initial) + + return ( +
+
+ + {(chip) => ( + + {chip} + } + aria-label={`Remove ${chip}`} + onClick={() => setChips((list) => list.filter((item) => item !== chip))} + /> + + )} + +
+