Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2aa46f21bf test(settings): include agentButton in the commit settings defaults shape 2026-11-20 13:29:14 +08:00
l0ng-ai 7310d0ab01 feat(vcs): setting to hide the Generate Commit Message with Agent button
Version Control › Commit › Commit Message Generation gets "Show the Generate Commit Message
with Agent button" (on by default). Off, the button above the commit message is hidden in
the Commit tool window and dialog; the action stays available from Find Action and its
shortcut.
2026-11-20 13:21:55 +08:00
l0ng-ai 2c6329012a fix(vcs): keep each repository's branch submenu expansion separate (#4694)
In multi-repository projects every repository's branch submenu read and wrote the same expansion state, so expanding Remote or a folder in one (e.g. to check out a remote branch) expanded it in all others. Each repository's submenu now keeps its own expansion (keys scoped by repository root); the single-repository popup keeps its saved state.
2026-11-20 12:57:30 +08:00
l0ng-ai f40bcd747f fix(database): complete columns of custom JDBC data sources (#4692)
SQL completion for custom JDBC data sources knew tables but no columns: the JDBC completion model left every table's columns empty (no alias. members, no WHERE columns, no SELECT * expansion). The bridge returns a namespace's columns in one DatabaseMetaData.getColumns call (schemaColumns) and the model fills each table; a driver refusing it still completes tables.
2026-11-20 12:27:41 +08:00
l0ng-ai c752f007be fix(run): show the compile errors when Update Application's build fails (#4691)
A failed Spring Boot / Tomcat update build only said "Application update build failed" and the Run tool window returned to the app's tab, hiding the reason. The notification now lists the compiler errors: from the Java language server's build, and from the Maven/Gradle update build's output (Maven, javac and Kotlin error lines, ANSI-stripped, de-duplicated, first ten). Notification bodies keep their line breaks.
2026-11-20 12:23:04 +08:00
l0ng-ai bcdff6886f fix(settings): organize editor appearance controls (#4687)
Editor > General > Appearance gets four titled sections (caret behavior, code structure, presentation, code assistance): line numbers and indent guides sit together, whitespace controls stay indented under their toggle, using the existing Settings section typography and spacing.
2026-11-20 12:21:02 +08:00
Deng Liuтаdengliu b7e9276b0f feat(agents): open model settings from the picker and composer (#4689)
The model picker showed settings only for the active model. Clicking the effort/context summary beside the model name now edits the current model directly, and each model row has an arrow that opens that model's settings without selecting it; changing a setting there selects the model and keeps the panel open, Back/Escape without an edit leaves the selection alone. Works in New Task and existing chats without sending the draft.

Co-authored-by: dengliu <[email protected]>
2026-11-20 12:19:53 +08:00
Muuтаmuutot 6023e391bc fix(editor): keep line-end annotations clear of a folded chip (#4688)
A header-line fold's chip is drawn at the same position as the zero-width anchors of line-end annotations, so the Code Vision hint, plugin line-end messages and inline blame painted over the chip and took its clicks. A shared foldChipWidth helper measures a chip drawn after an anchor and all three consumers step past it (Code Vision gains the MutationObserver the others already had).

Co-authored-by: muutot <[email protected]>
2026-11-20 12:15:57 +08:00
l0ng-ai 3d80e661b7 fix(search): keep Find results usable in narrow docks (#4681)
The pinned Find tool window moves its result actions to a vertical toolbar and the replacement controls to a wrapping footer. Wide docks show results beside the source preview, narrow docks stack them and remember the divider per layout; result rows use the editor code size and truncate long paths before file names and match counts.
2026-11-20 11:52:49 +08:00
zhzhsxтаzhzhsx b66439ceda fix(editor): keep the hover documentation from moving as it opens (#4682)
The hover documentation was placed twice: create() returned a popup holding only its toolbar, CodeMirror measured and placed it, and it moved once the text arrived. The body is now built in a layout effect and rendered before create() returns (flushSync), so the tooltip is measured once at its final size; the F1 popup and Documentation tool window share DocView and lose their empty first frame too.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 11:50:04 +08:00
l0ng-ai 899fe888b7 fix(docker): show container logs, processes and image layers without the docker CLI (#4686)
Engine API connections (SSH tunnel, socket, TCP) still ran docker logs / top / image history, failing on machines without the docker CLI. These now use the Engine API when the CLI is missing: logs stream and follow over their own connection (chunked encoding and per-stream frames, or a TTY's raw stream, cancellable); processes and image layers come from /top and /history. Refs #4648.
2026-11-20 11:46:36 +08:00
l0ng-ai e7de2aaf6d fix(docker): disable a container's actions while one runs on it (#4685)
Container actions gave no feedback while a slow (remote) daemon worked, inviting repeated or conflicting clicks. A container is now held busy from the request until the following snapshot: its actions are disabled in the dashboard, Services toolbar and context menu, the running one shows a spinner, and a second request is ignored. Compose actions are disabled while a Docker task runs. Refs #4648.
2026-11-20 11:46:30 +08:00
l0ng-ai 9293b13737 feat(vcs): show the Rollback Changes files as a checkable tree (#4684)
Rollback Changes listed the files flat. It now uses the checkable change tree of the Shelve and Create Patch dialogs: files grouped by directory under the repository, with tri-state boxes on repository and directory rows; the summary follows the selection.
2026-11-20 11:45:27 +08:00
l0ng-ai d1f79d05b3 fix(project-tree): add Manage Remotes and Clone to the Project view's Git menu (#4680)
The Project view's Git submenu stopped at Stash / Unstash; it now ends with Manage Remotes… and Clone…, like the editor's Git submenu and IDEA's Git context menu. Covered by a new e2e test in editorGitMenu.spec.ts.
2026-11-20 11:39:28 +08:00
l0ng-ai 176c43c908 fix(editor): make the paste history preview resizable (#4677)
Paste from History gives the preview more room by default and remembers the divider position (a resizable split). Delete moves beside the filter as a toolbar button; the snippets and preview use the active editor's font and zoom, and the preview drops line numbers to use its full width.
2026-11-20 11:33:27 +08:00
Nc 20b6b0aed5 fix(maven): sort sidebar profiles by ID (#4679)
The Maven sidebar listed profiles in model order. Profiles within each project group now sort by ID ignoring case, as IntelliJ's Maven tool window does; the -P argument keeps the model order.

Co-authored-by: qiany-sui <[email protected]>
2026-11-20 11:30:31 +08:00
l0ng-ai 101a0862e4 fix(database): reconnect a custom JDBC data source whose session was lost (#4675)
When a proxy or tunnel dropped an idle custom JDBC connection, every later statement failed and the source still showed Connected: the cached pool was only marked closed when the IDE closed it. After a failed statement the bridge now checks Connection.isValid (new valid op); an invalid or orphaned session closes the pool so the next statement or Connect reconnects. Keep-alive for JDBC uses the same check (and its option shows in the dialog); failures log at info.
2026-11-20 11:29:35 +08:00
Bin b48f0b6071 fix(vcs): enlarge deleted line marker hit area (#4669)
The deleted-lines marker is drawn above its gutter row, but clicks were resolved from the pointer's row, so clicking the triangle near the line boundary could miss the deletion. The marker gets a 12x12 transparent hit area (same triangle) with a pointer cursor, and clicks on it resolve to the deletion's row. Verified with vcs hunks and editor cm vitest, typecheck, and in the app (clicking the marker's upper half opens the Deleted lines popup).

Co-authored-by: ffgenius <[email protected]>
2026-11-20 11:23:37 +08:00
l0ng-ai a9b16c3e06 fix(debugger): keep call stack locations visible in narrow docks (#4671)
Call stack locations stay visible in narrow debug docks. Verified with e2e debugStackLayout, debugger vitest and typecheck.
2026-11-20 11:13:32 +08:00
l0ng-ai abd55f88b5 fix(search): make the editor switcher fit the workbench (#4660)
The editor switcher fits the workbench. Verified with e2e switcherLayout, search vitest and typecheck.
2026-11-20 11:13:20 +08:00
l0ng-ai dac4db0994 fix(settings): separate file type associations from ignore rules (#4657)
File Types settings separate file type associations from ignore rules. Verified with e2e fileTypesLayout, settings/locales vitest and typecheck.
2026-11-20 11:13:08 +08:00
Deng Liuтаdengliu b0d0ea868b feat(agents): configure GitHub Copilot authentication account (#4663)
Copilot launched with whichever GitHub CLI account was active outside the IDE. GitHub Copilot's settings get a GitHub account field: at launch the IDE asks gh for that account's token and passes it as COPILOT_GITHUB_TOKEN, without storing it; the account (not a credential) is kept with the agent's settings and scopes the catalog cache. Also adds the field's text to the en/zh catalog. Verified with cargo test -p ide-agent, clippy, agents and locale vitest, typecheck, and the field in Settings › Agents › Coding Agents.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:11:05 +08:00
Deng Liuтаdengliu d86ff872af fix(agents): recover model controls for fallback sessions (#4662)
A session whose agent fell back to a configuration without a model option kept a stale model label and offered no way to pick another model. The composer rebuilds the model control from the provider's catalog and set_config accepts a model from that catalog, switching through the same path as other discovered models. Verified with cargo test -p ide-agent, clippy, agents vitest and typecheck.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:07:37 +08:00
Deng Liuтаdengliu dbef3cdc96 fix(agents): support Auto-only Copilot catalogs (#4661)
Copilot can return an enabled Auto tier with an empty direct-model list; the catalog parser treated that as an empty catalog and forced the fallback transport. An enabled Auto tier now yields the auto model. Verified with cargo test -p ide-agent copilot and clippy.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:06:32 +08:00
C3B6 c483c3b76f perf(http-client): limit cached response details to four (#4659)
The HTTP Client kept every exchange's full request and response in memory for the whole session, even after its row left the backend's 100-entry history. The history list is capped at 100 like the backend, and only the four most recently viewed exchanges keep their details; older rows reload theirs from the saved history (which stores the full exchange) when selected. Verified with http-client vitest and typecheck.

Co-authored-by: 0xC3B6 <[email protected]>
2026-11-20 11:05:24 +08:00
HEOJUNFO da79a73def fix(http-client): keep the whole value of a Spring params/headers condition (#4666)
Spring params/headers conditions were split with split("=", 2), which drops everything after a second '='; only the first '=' divides name and value now, as in Spring. Verified with http-client vitest.

Co-authored-by: HEOJUNFO <[email protected]>
2026-11-20 11:04:44 +08:00
akshathayadav378-boopтаakshathayadav378-boop 2cc54b35f6 test(markdown): allow large render test to finish (#4664)
The large Markdown re-render test renders plugins/README.md repeatedly and can exceed Vitest's default 5 s timeout under full-suite load; it gets a 20 s timeout like other heavy tests.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 11:04:36 +08:00
zhzhsxтаzhzhsx 097221c1b3 fix(editor): colour Go's default like the other keywords (#4654)
@lezer/go tags every keyword except default, and gopls sends no keyword semantic tokens, so default in a Go switch/select rendered as plain text. Go now gets an extra style tag for default. Verified with editor cm vitest and typecheck.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:25:05 +08:00
l0ng-ai 1bb4ffe6b2 Keep the color scheme preview visible while editing (#4653)
The color scheme preview stays visible while editing scheme options. Verified with e2e colorSchemeLayout/editorFontLayout, settings and platform vitest and typecheck; main merged in (locale conflict resolved).
2026-11-20 10:22:05 +08:00
l0ng-ai 51e525336b Keep Welcome project search and actions in one row (#4652)
Welcome project search and actions stay in one row. Verified with e2e welcomeProjectsLayout, full vitest and typecheck.
2026-11-20 10:21:06 +08:00
l0ng-ai 1b47bc2c14 Keep the editor font preview visible while changing settings (#4649)
The editor font preview stays visible while changing font settings. Verified with e2e editorFontLayout, full vitest and typecheck.
2026-11-20 10:20:59 +08:00
l0ng-ai aa1326496b Show both commit ranges in Git branch comparisons (#4642)
Git branch comparison shows both commit ranges side by side in resizable panes. Verified with e2e branchCompareLayout, full vitest and typecheck.
2026-11-20 10:20:51 +08:00
leenтаleen2175 7850429174 fix(vcs): open existing worktrees over SSH (#4465)
Opening a linked worktree from an SSH or WSL project treated the remote directory as a local path. The Worktrees toolbar, row double-click and the checkout prompt's Open now go through openWorktree, which reuses the session's remote target and opens a remote window; local projects are unchanged. Verified with vcs and remote-dev vitest and typecheck on macOS (local path); the SSH flow was verified by the author in the native Linux app.

Co-authored-by: leen2175 <[email protected]>
2026-11-20 10:17:09 +08:00
Mansur Akhmadiтаmansur-akhmadi 3dd5c75fa0 feat(debugger): Remove All Watches in the Variables view's context menu (#4647)
A watch row's context menu in the Variables view gets Remove All Watches next to Remove Watch; it empties the project's stored watch list. Verified with debugger and locale vitest and typecheck; main merged in (locale conflict resolved).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:56 +08:00
Mansur Akhmadiтаmansur-akhmadi 36ecb53159 feat(run): Fold Lines Like This in the Run console's context menu (#4635)
The Run console's context menu gets Fold Lines Like This: it opens Settings › Build, Execution, Deployment › Console with the selected single-line text, or the right-clicked line, added to the fold patterns. Verified with full vitest, typecheck, and in the app (pattern added, Cancel leaves settings unchanged).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:00 +08:00
006405ca11 fix(remote): restore WSL projects onto a live connection (#4103)
* fix(remote): restore WSL projects onto a live connection

A reopened WSL window kept sending commands to a remote host it was no
longer connected to. Remember the remote location, and do not drop a
connection that a later open or a superseded attempt still needs.

Co-authored-by: Cursor <[email protected]>

* Use ? for the last remote location prefix (clippy::question_mark)

* fix(remote): save window session after connecting

---------

Co-authored-by: 胡长贵 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
2026-11-20 10:12:35 +08:00
Mollo-i 40b95650cf fix(maven): custom project.* properties and bare built-in shorthands resolve to their definition (#4651)
Every project.* name was treated as a Maven built-in, so custom properties such as project.port never navigated, and the bare built-in shorthand (@artifactId@) did not either. Non-coordinate project.* names now fall through to the <properties> lookup along the parent chain, and the bare shorthand resolves to the pom's own coordinate unless a custom property of that name exists. Verified with cargo test -p ide-build (maven tests pass; the one failing Go workspace test is unrelated to this change and fails from the local go toolchain) and clippy.

Co-authored-by: Greenker <[email protected]>
2026-11-20 10:08:09 +08:00
zhzhsxтаzhzhsx 0a571c0b4d fix(libraries): keep a Go module inside the project editable (#4639)
go list -m reports a replace target's own folder as the module's Dir, so a local replacement inside the project was registered as a read-only library root. Modules whose source sits inside the opened project (outside vendor/) are no longer library roots. Also passes the project root in the zig_groups test added on main. Verified with cargo test -p ide-sdk (new go_modules test passes; three go command tests fail the same way without this change, from the local go shim) and clippy.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:06:44 +08:00
l0ng-ai b1f88bf79c Separate shelves from the files they contain (#4640)
Shelf tool window separates the list of shelves from the files of the selected shelf in resizable panes. Verified with e2e shelfLayout, full vitest and typecheck.
2026-11-20 09:21:25 +08:00
l0ng-ai 0a6b3d011f Keep plugin list and details visible in narrow settings (#4636)
Plugins settings keep the list and details visible in narrow settings with a resizable split. Verified with e2e pluginsLayout, plugins/settings/locales vitest and typecheck.
2026-11-20 09:17:56 +08:00
l0ng-ai fd9b20fa05 Give interactive rebase plans and messages separate panes (#4637)
Interactive rebase shows the plan and the commit message in separate resizable panes. Verified with e2e interactiveRebaseLayout, full vitest and typecheck.
2026-11-20 09:17:14 +08:00
l0ng-ai 4f5622d72c refactor(agents): remove playful words from the working status (#4555)
Removes Settings › Agents › Working Status and its playfulStatus / playfulAfterSeconds / playfulWords settings. The line under a working conversation keeps saying what the agent is doing (Reading…, Running a command…); stored values of the removed settings are ignored.
2026-11-20 09:13:57 +08:00
l0ng-ai f4a7a7bafb perf(ui): smoother editor scrolling, tab switching and first file open (#4633)
Removes selectors that restyled whole subtrees on every inserted editor line or focus change (CodeMirror via a pnpm patch; selectorCost.test.ts guards them), measures space width once per font, shares one tooltip host, builds tab menus lazily, caches parsed SVG icons, prewarms an off-screen editor at idle, stats project-tree entries in parallel, and keeps the Git tool window at its size during a live window resize. Verified with full vitest, typecheck, ide-vfs cargo test and clippy, gitLog e2e, and a window resize in the app.
2026-11-20 09:13:29 +08:00
l0ng-ai 737afc6a8d Keep keymap search and shortcuts readable in narrow settings (#4632)
Keymap settings group the scheme selector with its actions and move the search controls to a second line in narrow settings; long action names scroll inside the tree. Verified with e2e keymapLayout/compactSettingsControls, settings vitest and typecheck.
2026-11-20 09:11:52 +08:00
l0ng-ai 6bf75155b6 Keep hierarchy symbols and source context readable (#4630)
Hierarchy view keeps symbol names and source context readable in narrow panes. Verified with e2e hierarchyLayout, code-insight vitest and typecheck.
2026-11-20 08:26:29 +08:00
l0ng-ai bbedf7e1f6 Make Inspections panes fit narrow settings windows (#4629)
Inspections settings panes resize and fit narrow settings windows. Verified with e2e inspectionsLayout/settingsFormLayout, full vitest and typecheck.
2026-11-20 08:26:21 +08:00
l0ng-ai 42fd0fa8e0 Organize Code Style settings into tabs (#4627)
Code Style settings are organized into tabs. Verified with e2e codeStyleLayout, settings vitest and typecheck.
2026-11-20 08:22:50 +08:00
l0ng-ai 97a41ae983 Give line bookmark text room in the tool window (#4624)
Bookmarks tool window rows give line bookmark text room. Verified with e2e bookmarkTreeLayout, search vitest and typecheck.
2026-11-20 08:22:42 +08:00
l0ng-ai f29903b698 Give the Stash dialog room for branch names and messages (#4623)
Stash dialog gives branch names and the message field room. Verified with e2e stashDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:35 +08:00
l0ng-ai 610fe23f88 Make the Pull dialog fit long branch names (#4622)
Pull dialog wraps long branch names instead of overflowing. Verified with e2e pullDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:26 +08:00
l0ng-ai 59376b9718 Improve the Update Project dialog layout (#4621)
Update Project dialog options and actions lay out cleanly at any width. Verified with e2e updateProject, vcs vitest and typecheck.
2026-11-20 08:22:18 +08:00
l0ng-ai 170fd735dd fix(vcs): keep clone fields usable in narrow dialogs (#4618)
Clone dialog fields stay usable and inside the dialog in narrow windows. Verified with e2e cloneLayout, vcs vitest and typecheck.
2026-11-20 08:22:11 +08:00
l0ng-ai e0ae9e764c fix(app): fit the New Project wizard in narrow windows (#4617)
The New Project wizard's template form fits narrow windows and keeps edits when resized. Verified with e2e newProjectLayout, app vitest and typecheck.
2026-11-20 08:07:19 +08:00
l0ng-ai 19c1b72650 fix(settings): fit SDK details within Project Structure (#4616)
Project Structure SDK details now wrap and stay inside the pane in narrow windows; the Home Path row reuses the shared path field. Verified with e2e projectSdkLayout/sdkFieldLayout, settings vitest and typecheck.
2026-11-20 07:53:11 +08:00
lleviathe 06ff2e51c3 fix(editor): even out the spacing of editor tabs (#4606)
Editor tabs sit 4px apart and keep an 18px close slot at one edge: before the icon when the close button is on the left, after the label when it is on the right, so switching sides no longer resizes tabs. The drag ghost keeps the strip's classes so it renders with the same layout. Verified with e2e editorTabClose/editor, src/ui vitest, typecheck, and both close positions in the app.

Co-authored-by: lleviathe <[email protected]>
2026-11-20 07:52:02 +08:00
l0ng-ai 6ae31b8148 test(keymap): list Shelve/Unshelve Silently in the VS Code and Eclipse presets (#4628)
#4620 added vcs.shelveSilently and vcs.unshelveSilently to the IntelliJ keymaps only, so the check that the VS Code preset covers every IntelliJ action id failed on main. Both the VS Code (macOS) and Eclipse (Windows) presets now list them unbound, like the other changelist actions.
2026-11-20 07:42:36 +08:00
Mansur Akhmadiтаmansur-akhmadi 3783b601b5 feat(vcs): copy a path from its repository's root in Copy Path/Reference… (#4626)
Copy Path/Reference... gains Path From Repository Root, as in IDEA: each selected path relative to the root of the Git repository holding it (innermost for nested repositories, a repository root as '.'), one per line, through the same copyPath menu group the hosting link uses. Paths outside every repository are left out, and the item is hidden when none is inside one.

Closes #4625

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 07:38:35 +08:00
l0ng-ai 37044dcd89 fix(vcs): give Local History diffs room in narrow panes (#4613)
Local History gave its revision list a fixed share of the pane, so in narrow panes the diff had little room and long labels were clipped. The list and diff are now a resizable split with sensible minimums, revision rows truncate with full text in tooltips, and the diff keeps room in narrow panes.
2026-11-20 07:37:21 +08:00
l0ng-ai 1a2adab237 fix(editor): align Reformat Code dialog groups and controls (#4611)
The Reformat Code dialog's option groups and controls were laid out ad hoc, so labels and checkboxes misaligned and the scope group wrapped awkwardly. The dialog now uses shared dialog fieldsets with aligned groups and controls, the same as the other analysis dialogs.
2026-11-20 07:12:25 +08:00
l0ng-ai 9ed87d77a7 fix(project-tree): make the Move dialog readable in narrow windows (#4609)
The Move dialog's title, target field and validation were laid out for a wide window, so in narrow ones the path and Browse button were clipped. The dialog now names what it moves (file, directory or N items), the target row wraps with its Browse button, and invalid targets (a folder into itself, the same directory) are explained inline.
2026-11-20 06:55:23 +08:00
Mansur Akhmadiтаmansur-akhmadi 9f4731189d feat(vcs): Shelve Silently and Unshelve Silently (#4620)
Shelving and unshelving always opened a dialog. As in IDEA, Shelve Silently (Changes toolbar, Ctrl+Shift+H / Shift+Cmd+H) shelves the Commit selection, or the active changelist, without a dialog, one shelf per changelist named as the Shelve dialog would suggest; Unshelve Silently (Ctrl+Alt+U / Opt+Cmd+U in the Shelf) applies the selected shelf or file into the matching changelist and honours Remove applied files from the shelf. The Shelve and Unshelve dialogs share the same helpers, and both actions are in the IntelliJ keymaps and IDEA_ACTIONS.

Closes #4619

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 06:39:35 +08:00
l0ng-ai 92ccfac192 fix(debugger): keep breakpoint details usable in narrow windows (#4605)
The Breakpoints dialog had a fixed list width beside the details, so in narrow windows locations were clipped and the details' controls ran off the dialog. The list and details are now a resizable split that stacks vertically below 560px (each layout remembered), the dialog itself can be resized, and locations show the file name and line with the full path in the tooltip.
2026-11-20 06:38:09 +08:00
l0ng-ai 60d335eec0 fix(refactor): keep the Change Signature parameter table readable (#4602)
The Change Signature dialog's parameter table had fixed column widths and a one-line preview, so in narrow windows types and names were clipped and long signatures ran off the preview. The table columns now share the width with truncation, the preview puts each parameter on its own line as IDEA's does, and the dialog's sections keep their controls visible.
2026-11-20 06:05:24 +08:00
Hafiz Faizan ul hassanтаfaizanalhassan a679e8086f feat(database): pick data source, then database and schema in the query console (#4614)
The query console's Data source dropdown mixed databases into the source list, and SQL Server's second dropdown listed databases. As in DataGrip, the dropdown now lists data sources only, and a database.schema switcher next to it opens a searchable database -> schema tree that loads a database's schemas on expand and moves the console to the picked database; one-level drivers keep a flat schema list and SQLite has none. SQL Server's console schema is now a real schema (SCHEMA_NAME()) that scopes resolution and completion, since a session's default schema can't be changed, while the pooled connection still returns to its database. Tree speed search also opens with Cmd/Ctrl+F, as in IDEA.

Closes #4577

Co-authored-by: faizanalhassan <[email protected]>
2026-11-20 06:04:34 +08:00
Mr0Bread 4c20aa5c8d test(editor): cover missing-file and malformed session restore (#4615)
Adds regression tests for editor session recovery: a deleted selected file is dropped quietly and the remaining tab restores with its caret, a permission-denied tab stays open with its error inline, and truncated session JSON loads as null without writing storage until a valid session replaces it. No production changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 06:00:56 +08:00
l0ng-ai d19d74120b fix(debugger): keep values visible in narrow variables panes (#4600)
In narrow Variables panes the name and type kept their full width, so values were cut to nothing and the Show button could be pushed out. Names and types now truncate within caps, the value and its Show button share a group that keeps a minimum width, overflow is measured against that group, and full names and types are in tooltips.
2026-11-20 06:00:12 +08:00
Mr0Bread 4e1cec5233 refactor(ipc): enforce typed error-kind comparisons (#4612)
IPC error kinds were compared as untyped strings (`(e as { kind?: string }).kind === "notFound"`), so a misspelt kind compiled and silently never matched. A typed `isErrorKind(error, kind)` helper, taking a kind from the generated `IdeError["kind"]`, now handles wrapped and raw IPC errors in document sync, editor session restore, Spring service identity, plugin commands and recent projects.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:41:29 +08:00
l0ng-ai 150eacc3de fix(editor): keep parameter info readable in narrow panes (#4599)
Parameter Info had a fixed 640px cap and a 12-signature window, so in narrow panes it overflowed the editor and long signatures were clipped. The popup now fits the editor's tooltip bounds and height, uses the editor's current font size, wraps long signatures with a hanging indent, scrolls when needed and keeps the current parameter in view.
2026-11-20 05:40:20 +08:00
l0ng-ai d1cc3cf68a fix(vcs): make merge panes resizable and keep actions visible (#4597)
The merge editor's three panes had fixed widths with decorative dividers, so in narrow windows they could not be resized and the toolbar actions overflowed. The panes are now a SplitGroup whose two handles carry the connector bands, each pane has its own title (branch and side), and the toolbar status is announced.
2026-11-20 05:25:12 +08:00
Mr0Bread 7c00ce4fa1 test(e2e): enforce TypeScript contract checking (#4610)
The e2e TypeScript project was never type checked: its tsconfig didn't inherit the app's settings, so @/ imports didn't resolve and hundreds of diagnostics went unnoticed. e2e/tsconfig.json now extends the root config (plus Node/Vite types and ES2024), pnpm typecheck runs tsrs -p e2e, and the remaining real type errors in the specs and fixtures are fixed; the code-style docs list the new project.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:19:07 +08:00
l0ng-ai 6539a95cb8 fix(vcs): keep push review readable in narrow windows (#4594)
The Push dialog's commits, changed files and diff panes had pixel minimums and fixed options rows, so narrow or short windows clipped the review and the target controls. The commits and changes now stack vertically below 640px with their own remembered split, the changed files come before the commit details, panes use relative minimums, and the target bar, options and tag options wrap.
2026-11-20 05:07:24 +08:00
l0ng-ai 08613ca800 fix(debugger): keep evaluation results readable in short dialogs (#4592)
The Evaluate dialog's result had a 220px minimum height, so in short windows the dialog overflowed and the result and buttons were cut off. The dialog now caps its height to the window, the expression field scrolls within half of it, imports wrap, and the result takes the remaining space; the expression uses the editor font and its label is tied to the field.
2026-11-20 04:49:29 +08:00
l0ng-ai 1ad8b06a1a fix(markdown): keep the Project view clickable in Preview only (#4604)
In Preview only the editor panel stays mounted but hidden, with no separator. react-resizable-panels adds an implicit resize region between two enabled panels without a separator; with the hidden panel's rect at zero it spanned everything left of the preview, showing a resize cursor and swallowing clicks in the Project view. The hidden editor panel is now disabled, leaving the group a single resizable panel.

Fixes #4589
2026-11-20 04:35:55 +08:00
l0ng-ai 2ca0e195e5 fix(editor): keep inline find controls inside narrow panes (#4588)
The inline find/replace bar used a fixed grid with a 220px minimum field, so in narrow editor panes the counter, option buttons and Close spilled outside the pane. The bar is now a container-query layout: fields shrink, the action groups wrap, and below 500px (and again below 224px) the actions and replace field move to their own rows while Show Replace and Close stay reachable.
2026-11-20 04:33:34 +08:00
Mr0Bread 750d35dd6e fix(vcs): discard stale status after project switch (#4598)
The VCS store reset on project switch, but replies to refreshes started for the previous project still wrote to it, restoring its branch, changed files and decorations and firing conflict notifications. A project generation, bumped on every switch (also when reopening the same folder), now gates full and incremental refresh results, errors and discovered roots; queued paths are dropped on switch, and the refresh queue still drains for the active project.

Closes #4596

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 04:10:23 +08:00
l0ng-ai f0273690b9 fix(run): keep test results readable in narrow panes (#4586)
The test tree's header held the counts, duration and every toolbar action in one 28px row, so narrow Run panes clipped the counts and buttons. As in IDEA's new layout, the status (icon, counts, total duration) now sits above the console, Expand All, Collapse All and Export Test Results move into a More Actions menu, and the tree and console stack vertically below 560px with their own remembered split.
2026-11-20 04:07:52 +08:00
331 змінених файлів з 12349 додано та 4088 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -5017,6 +5017,7 @@ dependencies = [
"ignore",
"notify",
"parking_lot",
"rayon",
"rustix",
"serde",
"serde_json",
+1 -1
Переглянути файл
@@ -51,7 +51,7 @@ async fn run_once(
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
})
.await
.map_err(|e| e.to_string())?;
.map_err(|e| e.to_string())??;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
let client = Dialect::wrap(updates.clone());
+28 -11
Переглянути файл
@@ -132,6 +132,7 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
github_account: Option<String>,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
@@ -193,6 +194,7 @@ impl Shared {
let metadata = std::fs::metadata(&executable).ok();
CopilotBinaryKey {
command: executable.to_string_lossy().into_owned(),
github_account: provider::copilot_github_account(&spec.env),
modified: metadata.as_ref().and_then(|m| m.modified().ok()),
len: metadata.as_ref().map(std::fs::Metadata::len),
}
@@ -1126,6 +1128,16 @@ impl AgentManager {
/// Changes a session setting (model, mode…): right away when the agent runs, else when it next starts.
pub async fn set_config(&self, id: &str, option: &str, value: String) -> IdeResult<()> {
let task = self.task(id)?;
let provider = task.state.lock().task.provider.clone();
let discovered = self
.shared
.paths
.catalogs
.cached(&self.shared, &provider)
.config
.iter()
.find(|o| o.id == option && o.category.as_deref() == Some("model"))
.cloned();
let (target, change) = {
let mut s = task.state.lock();
let busy = s.busy;
@@ -1146,17 +1158,19 @@ impl AgentManager {
task.emit_task();
return Ok(());
}
let target = s
.task
.config
.iter()
.find(|o| o.id == option)
.ok_or_else(|| IdeError::not_found("no such setting"))?
.clone();
let session_target = s.task.config.iter().find(|o| o.id == option).cloned();
let recovered_model = session_target.is_none();
let target = match session_target {
Some(target) => target,
None if discovered.is_some() => discovered.unwrap(),
None => return Err(IdeError::not_found("no such setting")),
};
if s.pending_model.is_some() && config::is_per_model_option(&target) {
return Err(IdeError::invalid("This setting is not available on the selected model"));
}
if !target.values.iter().any(|v| v.value == value) {
if recovered_model {
(target, None)
} else if !target.values.iter().any(|v| v.value == value) {
if target.category.as_deref() != Some("model") {
return Err(IdeError::invalid(format!("{} has no value {value}", target.name)));
}
@@ -2799,9 +2813,12 @@ impl Task {
pending_model: Option<&PendingModel>,
) -> Result<Live, SessionOpenError> {
let launch_cwd = cwd.to_path_buf();
let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
let mut spec = tokio::task::spawn_blocking(move || {
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
})
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| SessionOpenError { message: e, allow_acp_fallback: false })?;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
+2 -1
Переглянути файл
@@ -144,7 +144,8 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
})
.await
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?;
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
let args = headless_args(&launch.args);
let peer = Peer::spawn_framed(
+14 -2
Переглянути файл
@@ -312,7 +312,7 @@ impl Settings {
}
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
/// prepending `"auto"` when not already in the list.
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
let units = parse_price_units(price_units);
let raw = list
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
.map(Vec::as_slice)
.unwrap_or_default();
let mut out = Vec::new();
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
out.push(ModelEntry {
id: "auto".into(),
name: "Auto".into(),
@@ -344,6 +344,18 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
out
}
fn auto_model_available(list: &Value) -> bool {
let Some(auto) = list.get("auto") else { return false };
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
return false;
}
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
tiers.is_empty()
|| tiers.iter().any(|tier| {
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
})
}
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
let id = str_of(m, "id")?.to_owned();
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
+66
Переглянути файл
@@ -110,6 +110,72 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"displayName": "Standard",
"type": "auto",
"fusionTier": "standard",
"status": { "enabled": true, "pickerVisible": true }
},
{
"id": "hydrafusion",
"displayName": "High",
"type": "fusion",
"fusionTier": "high",
"status": {
"enabled": false,
"pickerVisible": true,
"reason": "user_not_eligible"
}
},
{
"id": "fast",
"displayName": "Fast",
"type": "auto",
"status": { "enabled": true, "pickerVisible": false }
}
],
"providerId": "copilot"
},
"imageModels": []
});
let catalog = models::parse_catalog(&list, None);
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
let options =
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
let model = options.iter().find(|option| option.id == MODEL).unwrap();
assert_eq!(model.current.as_deref(), Some("auto"));
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
}
#[test]
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"status": { "enabled": false, "pickerVisible": true }
}
]
}
});
assert!(models::parse_catalog(&list, None).is_empty());
}
#[test]
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
+129 -2
Переглянути файл
@@ -9,6 +9,8 @@ use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -138,15 +140,31 @@ impl ProviderSpec {
/// Resolve once before connecting, so authentication guidance names that same install.
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
let strip = prefer_stored_copilot_auth();
self.resolve_for_launch_with_copilot_env(cwd, strip)
self.resolve_for_launch_base(cwd, strip)
}
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
pub(crate) fn resolve_for_launch_with_copilot_env(
self,
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
}
Ok(resolved)
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
self.command =
@@ -164,6 +182,50 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
id == "copilot" || id.starts_with("copilot-")
}
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
env.iter()
.rev()
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
.map(|(_, value)| value.trim())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
fn github_token_for_account(account: &str) -> Result<String, String> {
let path = ide_core::process::shell_env()
.find(|(name, _)| name == "PATH")
.map(|(_, value)| value)
.or_else(|| ide_core::process::host_var_os("PATH"));
let program = path
.as_deref()
.and_then(|path| ide_core::process::find_executable("gh", path))
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command
.output()
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.trim();
return Err(if detail.is_empty() {
format!("GitHub CLI has no authenticated account named {account}")
} else {
format!("Couldn't use GitHub account {account}: {detail}")
});
}
let token = String::from_utf8(output.stdout)
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
let token = token.trim();
if token.is_empty() {
return Err(format!("GitHub CLI returned no token for account {account}"));
}
Ok(token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -339,6 +401,31 @@ pub(crate) fn set_builtin_env(
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
if id == "copilot" {
let file = custom_dir.join("copilot.toml");
if file.try_exists()?
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
&& agent.registry.is_some()
{
let existing = agent.env.clone();
let mut existing_launch_env = existing.clone();
let mut next_launch_env = env.clone();
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
if existing_launch_env != next_launch_env {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
Some(account) => {
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
}
None => {
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
}
}
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
}
@@ -955,6 +1042,46 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("copilot.toml");
CustomAgent {
name: Some("GitHub Copilot".into()),
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
.write(&file)
.unwrap();
set_builtin_env(
dir.path(),
None,
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
]),
)
.unwrap();
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
}
#[test]
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
let mut spec = builtin_spec("copilot").unwrap();
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
+8
Переглянути файл
@@ -537,6 +537,14 @@ fn install_entry_with(
return Err(e);
}
};
let github_account = (entry.id == "copilot")
.then(|| CustomAgent::read(&file).ok())
.flatten()
.and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned());
let mut env = env;
if let Some(account) = github_account {
env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account);
}
let agent = CustomAgent {
name: Some(entry.name.clone()),
driver: Driver::Acp,
+50
Переглянути файл
@@ -2333,6 +2333,56 @@ async fn idle_model_switches_discover_controls_and_no_control_models_without_ano
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_without_a_model_option_can_select_from_a_recovered_catalog() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
]);
let mgr = manager(tmp.path(), agent);
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude-acp".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let spec = mgr.shared.spec("claude-acp").unwrap();
let (_, flight) = mgr.shared.paths.catalogs.request(&mgr.shared, spec, true, None);
if let Some(mut ready) = flight {
tokio::time::timeout(Duration::from_secs(5), async {
while !*ready.borrow_and_update() {
ready.changed().await.unwrap();
}
})
.await
.unwrap();
}
{
let task = mgr.task(&task.id).unwrap();
let mut state = task.state.lock();
state.task.config.retain(|option| option.category.as_deref() != Some("model"));
state.task.model = Some("stale-model".into());
}
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
let task = mgr.task(&task.id).unwrap();
{
let state = task.state.lock();
assert_eq!(state.task.model.as_deref(), Some("small"));
let model = state.task.config.iter().find(|option| option.category.as_deref() == Some("model")).unwrap();
assert_eq!(model.current.as_deref(), Some("small"));
assert!(model.values.iter().any(|value| value.value == "small"));
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_model_discovery_failure_restores_the_previous_choice_without_claiming_no_controls() {
let tmp = tempfile::tempdir().unwrap();
+88 -11
Переглянути файл
@@ -2020,11 +2020,25 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
label: name.clone(),
});
}
// Built-in coordinates: the POM's own element, else the first ancestor declaring one.
if let Some(key) = name.strip_prefix("project.") {
if !matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") {
return None; // `project.basedir`, `project.build.directory`… have no element.
// Built-in coordinates (`project.artifactId`, and the bare `@artifactId@`
// shorthand resource filtering resolves the same way): the POM's own element,
// else the first ancestor declaring one. Any other name under `project.` is a
// custom property (`project.port`, `project.servlet.path`), which the
// `<properties>` lookup below resolves.
let built_in = match name.strip_prefix("project.") {
Some(key) if matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") => Some(key),
// `project.basedir`, `project.build.directory`… have no element of their own.
Some(_) => None,
None if matches!(name.as_str(), "groupId" | "artifactId" | "version" | "packaging" | "name") => {
// The bare shorthand of a built-in; a custom property of that name wins.
if let Some(found) = properties_target(&chain, &name, &resolver) {
return Some(found);
}
Some(name.as_str())
}
None => None,
};
if let Some(key) = built_in {
for (p, text) in &chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let Some(e) = root.child(key).filter(|e| !e.text.trim().is_empty()) else { continue };
@@ -2037,30 +2051,34 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
}
return None;
}
// A property of `<properties>`: the first POM of the chain (child-first) that
// declares it, at project level or in an active profile.
for (p, text) in &chain {
properties_target(&chain, &name, &resolver)
}
/// A property of `<properties>`: the first POM of the chain (child-first) that
/// declares it, at project level or in an active profile.
fn properties_target(chain: &[(PathBuf, String)], name: &str, resolver: &Resolver) -> Option<PomGoto> {
for (p, text) in chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let active: Vec<String> = parse_pom(text)
.map(|pom| resolver.active(&pom.profiles).map(|pr| pr.id.clone()).collect())
.unwrap_or_default();
// Project level first, then the first active profile declaring the property.
let e = root.child("properties").and_then(|props| props.child(&name)).or_else(|| {
let e = root.child("properties").and_then(|props| props.child(name)).or_else(|| {
root.list("profiles", "profile")
.into_iter()
.find(|profile| {
active.contains(&profile.child("id").map(|id| id.text.trim().to_owned()).unwrap_or_default())
&& profile.child("properties").and_then(|props| props.child(&name)).is_some()
&& profile.child("properties").and_then(|props| props.child(name)).is_some()
})?
.child("properties")?
.child(&name)
.child(name)
});
if let Some(e) = e {
return Some(PomGoto {
path: p.clone(),
range: range_of(text, e),
kind: PomGotoKind::Property,
label: name.clone(),
label: name.to_owned(),
});
}
}
@@ -3086,6 +3104,65 @@ mod tests {
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
}
#[test]
fn a_custom_project_property_is_found_like_a_plain_one() {
let text = format!(
r#"{CHILD_HEADER}<properties>
<project.port>8001</project.port>
</properties>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
<version>${{project.port}}</version>
</dependency>
</dependencies>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
let goto = goto_declaration(&text, path, at(&text, "${project.port}"), None).unwrap();
assert_eq!(goto.kind, PomGotoKind::Property);
assert_eq!(goto.label, "project.port");
assert_eq!(goto.path, path);
let from = text.find("<project.port>").unwrap();
let to = text.find("</project.port>").unwrap() + "</project.port>".len();
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
// `${project.basedir}` has no element and no custom property: still nothing.
let basedir = text.replace("${project.port}", "${project.basedir}");
assert_eq!(goto_declaration(&basedir, path, at(&basedir, "${project.basedir}"), None), None);
}
#[test]
fn the_bare_builtin_shorthand_resolves_to_the_coordinate_and_a_custom_property_wins() {
let text = format!(
r#"{CHILD_HEADER}<artifactId>app</artifactId>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
</dependency>
</dependencies>
<properties>
<groupId>custom</groupId>
</properties>
<description>${{artifactId}}-${{groupId}} docs</description>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
// `@artifactId@` in a filtered resource resolves to the own coordinate.
let goto = goto_declaration(&text, path, at(&text, "${artifactId}"), None).unwrap();
assert_eq!(goto.label, "artifactId");
let from = text.find("<artifactId>app").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
// A custom property of the bare name wins over the shorthand. The click
// sits inside the reference: the second one's `$` is behind the first's
// closing `}`, which `property_ref_at` does not take for the `$` itself.
let goto = goto_declaration(&text, path, at(&text, "groupId} docs"), None).unwrap();
assert_eq!(goto.label, "groupId");
let from = text.find("<groupId>custom").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
}
#[test]
fn an_inherited_property_reference_finds_its_definition_in_the_parent_pom() {
let tmp = tempfile::tempdir().unwrap();
-13
Переглянути файл
@@ -100,16 +100,6 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// While the agent works, playful words fill the pauses in what it reports.
pub playful_status: bool,
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
/// from the start.
pub playful_after_seconds: u32,
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
/// the built-in ones of that activity; an empty list keeps its status factual.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, Vec<String>>)]
pub playful_words: BTreeMap<String, Vec<String>>,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -152,9 +142,6 @@ impl Default for AgentSettings {
fold_turns: true,
smooth_text: true,
fit_window_width: false,
playful_status: false,
playful_after_seconds: 0,
playful_words: BTreeMap::new(),
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
+3
Переглянути файл
@@ -176,6 +176,8 @@ pub struct CommitSettings {
pub agent_model: String,
/// That model's thinking level for commit messages; empty keeps the agent's.
pub agent_effort: String,
/// Show the Generate Commit Message with Agent button above the commit message.
pub agent_button: bool,
}
impl Default for CommitSettings {
@@ -201,6 +203,7 @@ impl Default for CommitSettings {
agent: String::new(),
agent_model: String::new(),
agent_effort: String::new(),
agent_button: true,
}
}
}
+10 -1
Переглянути файл
@@ -217,7 +217,8 @@ impl ManageConnection for MssqlConnectionManager {
let row = client.simple_query("SELECT DB_NAME()").await?.into_row().await?;
let default = row
.and_then(|r| r.get::<&str, _>(0).map(str::to_owned))
.and_then(|db| crate::sql::use_schema(DbDriver::SqlServer, &db));
// Statements that `USE` another database must not move the pooled connection for good.
.map(|db| format!("USE {}", crate::sql::quote_ident(DbDriver::SqlServer, &db)));
Ok(MssqlConnection(Some(client), Context::new(default)))
}
@@ -748,6 +749,14 @@ impl Pool {
}
/// The keep-alive ping (Oracle needs a FROM clause).
/// Keep-alive: one cheap round trip on the session.
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
pub fn ping_sql(&self) -> &'static str {
match self {
Pool::Oracle(_) => "SELECT 1 FROM DUAL",
+91 -1
Переглянути файл
@@ -5,6 +5,7 @@ use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};
use std::process::Stdio;
@@ -458,6 +459,44 @@ impl JdbcPool {
}
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let result = self.exchange_once(fields, sql, cancel).await;
if let Err(e) = &result
&& fields.first() != Some(&"open")
&& e.kind != ide_core::error::ErrorKind::Cancelled
&& !self.is_closed()
&& !self.session_valid().await
{
// The session is gone (a proxy or tunnel dropped the idle TCP connection): close the
// pool so the next statement or Connect starts a new one instead of failing forever.
self.close().await;
}
result
}
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
pub(crate) async fn ping(&self) -> IdeResult<()> {
if self.session_valid().await {
return Ok(());
}
self.close().await;
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
}
/// Whether the JDBC session still works, asked after a failed statement.
async fn session_valid(&self) -> bool {
if self.bridge.lock().await.is_none() {
return false;
}
let cancel = CancellationToken::new();
match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await {
Ok(Ok(result)) => {
result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false")
}
Ok(Err(_)) | Err(_) => false,
}
}
async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
@@ -562,14 +601,26 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
impl DbManager {
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
let mut tables = vec![];
let mut column_count = 0;
let schemas = self.schemas(id).await?;
for schema in &schemas {
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
let mut columns = if column_count < crate::MAX_META_ROWS {
pool.metadata(&["schemaColumns", schema]).await.map(schema_columns).unwrap_or_else(|e| {
tracing::warn!("JDBC columns of {schema}: {}", e.message);
HashMap::new()
})
} else {
HashMap::new()
};
for table in self.tables(id, schema).await? {
let columns = columns.remove(&table.name).unwrap_or_default();
column_count += columns.len();
tables.push(crate::CompletionTable {
schema: schema.clone(),
name: table.name,
kind: table.kind,
columns: vec![],
columns,
});
if tables.len() >= crate::MAX_META_ROWS {
break;
@@ -594,10 +645,49 @@ impl DbManager {
}
}
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
for row in rows {
let mut it = row.into_iter();
let (Some(Some(table)), Some(Some(name))) = (it.next(), it.next()) else { continue };
let data_type = it.next().flatten().unwrap_or_default();
let nullable = it.next().flatten().as_deref() != Some("0");
let has_default = it.next().flatten().is_some();
by_table.entry(table).or_default().push(crate::CompletionColumn {
name,
data_type,
nullable,
primary_key: false,
has_default,
});
}
by_table
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_columns_group_by_table() {
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
};
let by_table = schema_columns(vec![
row("orders", "id", "0", None),
row("orders", "note", "1", Some("'none'")),
row("items", "sku", "1", None),
vec![None, Some("orphan".into())],
]);
let orders = &by_table["orders"];
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
assert_eq!(by_table["items"].len(), 1);
assert_eq!(by_table.len(), 2);
}
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
+12 -7
Переглянути файл
@@ -379,8 +379,8 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
loop {
tick.tick().await;
let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break };
if let Err(e) = p.rows(p.ping_sql(), 1).await {
tracing::debug!("keep-alive: {}", e.message);
if let Err(e) = p.ping().await {
tracing::info!("keep-alive: {}", e.message);
}
}
});
@@ -847,12 +847,12 @@ impl DbManager {
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().contains_key(id)
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().keys().cloned().collect()
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
@@ -862,8 +862,13 @@ impl DbManager {
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
if let Some(p) = self.pools.lock().get(id) {
return Ok(p.clone());
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
@@ -917,7 +922,7 @@ impl DbManager {
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.connected().into_iter().filter(|t| split_target(t).0 == id).collect();
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
+8 -6
Переглянути файл
@@ -442,7 +442,8 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
DbDriver::Sqlite | DbDriver::Jdbc => None,
DbDriver::Postgres => Some("SELECT current_schema()"),
DbDriver::Mysql => Some("SELECT DATABASE()"),
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
// The login's default schema; the database is the console's target (IDEA's `database.schema`).
DbDriver::SqlServer => Some("SELECT SCHEMA_NAME()"),
DbDriver::Oracle => Some("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL"),
DbDriver::Snowflake => Some("SELECT CURRENT_SCHEMA()"),
}
@@ -450,12 +451,13 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
/// The statement that makes unqualified names resolve in `schema` on the
/// connection that runs it (a query console's active schema; `None`: the driver
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs).
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs, and SQL Server
/// cannot change a session's default schema, so its console schema only scopes resolution).
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
match driver {
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc | DbDriver::SqlServer => None,
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Mysql => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))),
DbDriver::Snowflake => Some(format!("USE SCHEMA {}", quote_ident(driver, schema))),
}
@@ -1030,7 +1032,7 @@ mod tests {
assert_eq!(quote_ident(DbDriver::SqlServer, "a]b"), "[a]]b]");
assert_eq!(qualified(DbDriver::SqlServer, "dbo", "t"), "[dbo].[t]");
assert_eq!(qualified(DbDriver::SqlServer, "", "t"), "[t]");
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT DB_NAME()"));
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT SCHEMA_NAME()"));
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
assert_eq!(
schemas(DbDriver::SqlServer, true),
@@ -1149,7 +1151,7 @@ mod tests {
fn schema_switch_statement_per_dialect() {
assert_eq!(use_schema(DbDriver::Postgres, "app data"), Some("SET search_path TO \"app data\"".into()));
assert_eq!(use_schema(DbDriver::Mysql, "a`b"), Some("USE `a``b`".into()));
assert_eq!(use_schema(DbDriver::SqlServer, "app] data"), Some("USE [app]] data]".into()));
assert_eq!(use_schema(DbDriver::SqlServer, "dbo"), None);
assert_eq!(use_schema(DbDriver::Postgres, "a\"b"), Some("SET search_path TO \"a\"\"b\"".into()));
assert_eq!(use_schema(DbDriver::Oracle, "a\"b"), Some("ALTER SESSION SET CURRENT_SCHEMA = \"a\"\"b\"".into()));
assert!(sqlserver_databases().contains("state = 0 AND HAS_DBACCESS(name) = 1"));
+37 -1
Переглянути файл
@@ -90,7 +90,10 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
assert!(result.has_more);
assert_eq!(result.rows, vec![vec![Some("1".into()), None]]);
assert_eq!(result.columns[1].name, "label");
assert_eq!(db.completion("test").await?.default_schema, "main");
let completion = db.completion("test").await?;
assert_eq!(completion.default_schema, "main");
let items = completion.tables.iter().find(|t| t.schema == "main" && t.name == "items").expect("items");
assert_eq!(items.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "label"]);
db.execute("test", "create temporary table session_marker as select 42 as id", 1, &c).await?;
let stop = CancellationToken::new();
let (cancelled, ()) =
@@ -213,3 +216,36 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
let source = DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "fixture".into(),
url: "jdbc:fixture:".into(),
..Default::default()
};
db.save_sources(vec![source]).await?;
let cancel = CancellationToken::new();
db.execute("test", "first", 1, &cancel).await?;
// The fixture's session reports itself invalid after "drop", like a connection a proxy reset.
assert!(db.execute("test", "drop", 1, &cancel).await.unwrap_err().message.contains("connection reset"));
assert!(!db.is_connected("test"), "a lost session is no longer listed as connected");
assert_eq!(db.execute("test", "after reconnect", 1, &cancel).await?.affected, Some(1.0));
assert!(db.is_connected("test"));
db.disconnect("test").await;
Ok(())
}
+382 -9
Переглянути файл
@@ -7,9 +7,10 @@
use crate::{
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
DockerEndpoint, DockerImage, DockerNetwork, DockerObject, DockerSnapshot, DockerVolume, split_csv,
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
DockerSnapshot, DockerVolume, split_csv,
};
use ide_core::{IdeError, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::io::{Read, Write};
@@ -193,9 +194,15 @@ fn request(addr: &Address, method: &str, path: &str, timeout: Duration) -> IdeRe
read_response(&mut conn)
}
/// Reads an HTTP/1.1 response: head until `\r\n\r\n`, then the body per its
/// framing (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
/// A response's status line and body framing.
struct Head {
status: u16,
chunked: bool,
length: Option<usize>,
}
/// Reads an HTTP/1.1 response head until `\r\n\r\n`.
fn read_head(stream: &mut impl Read) -> IdeResult<Head> {
let mut head: Vec<u8> = Vec::new();
let mut byte = [0u8; 1];
loop {
@@ -228,16 +235,27 @@ fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
length = value.parse().ok();
}
}
let body = if chunked {
Ok(Head { status, chunked, length })
}
/// Reads an HTTP/1.1 response: its head, then the body per its framing
/// (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
let head = read_head(stream)?;
let body = read_body(stream, &head)?;
Ok(Response { status: head.status, body })
}
fn read_body(stream: &mut impl Read, head: &Head) -> IdeResult<Vec<u8>> {
Ok(if head.chunked {
read_chunked(stream)?
} else if let Some(n) = length {
} else if let Some(n) = head.length {
read_exact_n(stream, n)?
} else {
let mut body = Vec::new();
stream.read_to_end(&mut body)?;
body
};
Ok(Response { status, body })
})
}
/// Reads one `\n`-terminated line (returned without it).
@@ -482,6 +500,292 @@ pub(crate) fn inspect(
})())
}
/// The processes running in a container (`docker top`).
pub(crate) fn container_top(ep: &DockerEndpoint, id: &str, timeout: Duration) -> Option<IdeResult<DockerProcessList>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/containers/{}/top", path_segment(id)), timeout)?)?;
serde_json::from_str::<ApiTop>(&body)
.map(|t| DockerProcessList { titles: t.titles, processes: t.processes })
.map_err(|e| IdeError::internal(format!("the Docker daemon's process list is not JSON: {e}")))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiTop {
titles: Vec<String>,
processes: Vec<Vec<String>>,
}
/// An image's layers, newest first (`docker image history`).
pub(crate) fn image_history(
ep: &DockerEndpoint,
id: &str,
timeout: Duration,
) -> Option<IdeResult<Vec<DockerImageLayer>>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/images/{}/history", path_segment(id)), timeout)?)?;
let layers = serde_json::from_str::<Vec<ApiLayer>>(&body)
.map_err(|e| IdeError::internal(format!("the Docker daemon's image history is not JSON: {e}")))?;
Ok(map_layers(layers, unix_now()))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiLayer {
id: String,
created: i64,
created_by: String,
size: i64,
comment: String,
}
fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
layers
.into_iter()
.map(|l| DockerImageLayer {
id: l.id,
created_by: l.created_by,
size: human_size(l.size),
created_since: human_duration((now - l.created).max(0)),
created_at: unix_utc(l.created),
comment: l.comment,
})
.collect()
}
fn unix_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
/// How often a log stream that has nothing to read checks for cancellation.
const LOG_POLL: Duration = Duration::from_millis(200);
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerInspect {
config: ApiContainerConfig,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerConfig {
tty: bool,
}
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// from `ep`'s daemon until they end or `cancel` fires.
#[allow(clippy::too_many_arguments)]
pub(crate) fn logs(
ep: &DockerEndpoint,
id: &str,
tail: u32,
follow: bool,
timestamps: bool,
timeout: Duration,
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> Option<IdeResult<()>> {
let addr = address(ep)?;
Some((|| {
// A TTY container's log is one raw stream; otherwise it is framed per stream.
let body = check(request(&addr, "GET", &format!("/containers/{}/json", path_segment(id)), timeout)?)?;
let tty = serde_json::from_str::<ApiContainerInspect>(&body).map(|c| c.config.tty).unwrap_or(false);
let path = format!(
"/containers/{}/logs?stdout=1&stderr=1&tail={tail}&follow={}&timestamps={}",
path_segment(id),
u8::from(follow),
u8::from(timestamps),
);
let mut conn = Conn::connect(&addr, timeout)?;
conn.write_all(
format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n")
.as_bytes(),
)?;
let head = read_head(&mut conn)?;
if !(200..300).contains(&head.status) {
let body = read_body(&mut conn, &head)?;
check(Response { status: head.status, body })?;
}
conn.set_timeouts(LOG_POLL);
let mut decoder = LogDecoder::new(&head, tty);
let mut buf = [0u8; 8192];
while !decoder.done() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match conn.read(&mut buf) {
Ok(0) => break,
Ok(n) => decoder.feed(&buf[..n], &mut |line| on_line(line))?,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted
) => {}
Err(e) => return Err(e.into()),
}
}
decoder.finish(&mut |line| on_line(line));
Ok(())
})())
}
/// Turns a log response body, as it arrives, into lines: undoes the chunked
/// transfer encoding, then the per-stream frames (8-byte header: stream, 3 zero
/// bytes, big-endian length) unless the container has a TTY.
struct LogDecoder {
body: BodyFraming,
tty: bool,
header: Vec<u8>,
frame_left: usize,
frame_stderr: bool,
/// Partial lines of stdout and stderr.
partial: [Vec<u8>; 2],
}
enum BodyFraming {
Chunked { state: ChunkState, line: Vec<u8> },
Length(usize),
Close,
}
#[derive(Clone, Copy, PartialEq)]
enum ChunkState {
Size,
Data(usize),
DataEnd,
Trailer,
Done,
}
impl LogDecoder {
fn new(head: &Head, tty: bool) -> Self {
let body = if head.chunked {
BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() }
} else if let Some(n) = head.length {
BodyFraming::Length(n)
} else {
BodyFraming::Close
};
Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] }
}
fn done(&self) -> bool {
matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0))
}
fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
let mut payload = Vec::new();
match &mut self.body {
BodyFraming::Close => payload.extend_from_slice(bytes),
BodyFraming::Length(left) => {
let take = (*left).min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
*left -= take;
}
BodyFraming::Chunked { state, line } => {
while !bytes.is_empty() {
match *state {
ChunkState::Done => break,
ChunkState::Data(n) => {
let take = n.min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
*state = if take == n { ChunkState::DataEnd } else { ChunkState::Data(n - take) };
}
_ => {
let b = bytes[0];
bytes = &bytes[1..];
if b != b'\n' {
if b != b'\r' {
line.push(b);
}
continue;
}
let text = String::from_utf8_lossy(line).into_owned();
line.clear();
*state = match *state {
ChunkState::Size => {
let size = text.split(';').next().unwrap_or_default().trim();
match usize::from_str_radix(size, 16) {
Ok(0) => ChunkState::Trailer,
Ok(n) => ChunkState::Data(n),
Err(_) => {
return Err(IdeError::internal(
"the Docker daemon answered with a malformed chunked response",
));
}
}
}
ChunkState::DataEnd => ChunkState::Size,
_ if text.is_empty() => ChunkState::Done,
other => other,
};
}
}
}
}
}
self.frames(&payload, emit);
Ok(())
}
fn frames(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
if self.tty {
self.lines(false, bytes, emit);
return;
}
while !bytes.is_empty() {
if self.frame_left == 0 {
let take = (8 - self.header.len()).min(bytes.len());
self.header.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
if self.header.len() == 8 {
self.frame_stderr = self.header[0] == 2;
self.frame_left =
u32::from_be_bytes([self.header[4], self.header[5], self.header[6], self.header[7]]) as usize;
self.header.clear();
}
continue;
}
let take = self.frame_left.min(bytes.len());
self.lines(self.frame_stderr, &bytes[..take], emit);
self.frame_left -= take;
bytes = &bytes[take..];
}
}
fn lines(&mut self, stderr: bool, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
let partial = &mut self.partial[usize::from(stderr)];
for &b in bytes {
if b == b'\n' {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
} else {
partial.push(b);
}
}
}
/// Emits the last lines that ended without a newline.
fn finish(&mut self, emit: &mut dyn FnMut(DockerLogLine)) {
for stderr in [false, true] {
let partial = &mut self.partial[usize::from(stderr)];
if !partial.is_empty() {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
}
}
}
}
fn line_text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes.strip_suffix(b"\r").unwrap_or(bytes)).into_owned()
}
/// One URL path segment, percent-encoded so an id cannot change the path.
fn path_segment(id: &str) -> String {
let mut out = String::with_capacity(id.len());
@@ -817,6 +1121,75 @@ mod tests {
assert!(read_response(&mut &garbage[..]).is_err());
}
/// Feeds `body` one byte at a time, as a slow connection delivers it.
fn decode(head: Head, tty: bool, body: &[u8]) -> (Vec<(bool, String)>, bool) {
let mut lines = Vec::new();
let mut decoder = LogDecoder::new(&head, tty);
for b in body {
decoder.feed(std::slice::from_ref(b), &mut |l| lines.push((l.stderr, l.text))).unwrap();
}
let done = decoder.done();
decoder.finish(&mut |l| lines.push((l.stderr, l.text)));
(lines, done)
}
fn frame(stream: u8, text: &str) -> Vec<u8> {
let mut f = vec![stream, 0, 0, 0];
f.extend((text.len() as u32).to_be_bytes());
f.extend(text.as_bytes());
f
}
#[test]
fn engine_image_history_reads_like_the_cli() {
let layers: Vec<ApiLayer> = serde_json::from_str(
r#"[{"Id":"sha256:abc","Created":1000,"CreatedBy":"CMD [\"python3\"]","Size":20500,"Comment":"buildkit","Tags":["py:3"]},
{"Id":"<missing>","Created":940,"CreatedBy":"RUN x","Size":0,"Comment":""}]"#,
)
.unwrap();
let rows = map_layers(layers, 1000 + 2 * 7 * 86_400);
assert_eq!(
rows.iter().map(|l| (l.id.as_str(), l.size.as_str(), l.created_since.as_str())).collect::<Vec<_>>(),
[("sha256:abc", "20.5kB", "2 weeks ago"), ("<missing>", "0B", "2 weeks ago")]
);
assert_eq!(rows[0].created_by, "CMD [\"python3\"]");
let top: ApiTop = serde_json::from_str(r#"{"Titles":["PID","CMD"],"Processes":[["1","sh"]]}"#).unwrap();
assert_eq!(
(top.titles, top.processes),
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
);
}
#[test]
fn container_logs_split_into_stream_lines_across_chunks_and_frames() {
// Frames split mid-line, a CRLF line, and a stderr line between stdout parts.
let mut framed = frame(1, "tick 1\r\ntick");
framed.extend(frame(2, "oops\n"));
framed.extend(frame(1, " 2\nlast"));
let mut chunked = Vec::new();
for part in framed.chunks(7) {
chunked.extend(format!("{:x}\r\n", part.len()).as_bytes());
chunked.extend(part);
chunked.extend(b"\r\n");
}
chunked.extend(b"0\r\n\r\n");
let (lines, done) = decode(Head { status: 200, chunked: true, length: None }, false, &chunked);
assert!(done);
let expected = [(false, "tick 1"), (true, "oops"), (false, "tick 2"), (false, "last")];
assert_eq!(lines, expected.map(|(e, t)| (e, t.to_owned())));
// A TTY container's log is one raw stream; the body may end with the connection.
let (lines, done) = decode(Head { status: 200, chunked: false, length: None }, true, b"a\r\nb\n");
assert!(!done);
assert_eq!(lines, [(false, "a".to_owned()), (false, "b".to_owned())]);
// A Content-Length body ends after its length.
let body = frame(1, "one\n");
let (lines, done) = decode(Head { status: 200, chunked: false, length: Some(body.len()) }, false, &body);
assert!(done);
assert_eq!(lines, [(false, "one".to_owned())]);
}
#[test]
fn daemon_errors_carry_their_message() {
let resp = Response { status: 404, body: br#"{"message":"No such container: missing"}"#.to_vec() };
+15
Переглянути файл
@@ -287,6 +287,11 @@ fn check_id(id: &str) -> IdeResult<&str> {
/// `docker image history --no-trunc --format '{{json .}}'` of one image.
pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImageLayer>> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(layers) = engine::image_history(ep, id, QUICK)
{
return layers;
}
let out = run(ep, &["image", "history", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
Ok(parse_image_history(&out))
}
@@ -294,6 +299,11 @@ pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImage
/// `docker top <id>` of a running container.
pub fn container_top(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerProcessList> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(processes) = engine::container_top(ep, id, QUICK)
{
return processes;
}
let out = run(ep, &["top", id], QUICK)?;
Ok(parse_container_top(&out))
}
@@ -316,6 +326,11 @@ pub fn logs(
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> IdeResult<()> {
if docker_executable().is_none()
&& let Some(streamed) = engine::logs(ep, id, tail, follow, timestamps, QUICK, cancel, on_line)
{
return streamed;
}
let tail = tail.to_string();
let mut args = vec!["logs", "--tail", &tail];
if follow {
+25 -12
Переглянути файл
@@ -84,7 +84,7 @@ pub fn project_libraries_stream(
cancel: &CancellationToken,
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
type Detect = fn(&Path, &Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups, zig_groups];
let roots = library_project_roots(root, cancel);
let settings = module_settings(root, settings);
@@ -99,7 +99,7 @@ pub fn project_libraries_stream(
if cancel.is_cancelled() {
break;
}
let batch = d(dir, settings, cancel);
let batch = d(dir, root, settings, cancel);
if !cancel.is_cancelled() && !batch.is_empty() {
on_groups(batch.clone());
groups.extend(batch);
@@ -384,7 +384,7 @@ fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
// ------------------------------------------------------------------ python
fn python_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn python_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
let mut files = vec![python.clone()];
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
@@ -436,7 +436,7 @@ pub(crate) fn named_roots(roots: Vec<(String, PathBuf)>) -> Vec<LibraryRoot> {
// ------------------------------------------------------------------ ruby
fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn ruby_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, RUBY_MANIFESTS) else { return Vec::new() };
if !root.join("Gemfile").is_file() && !root.join(".ruby-version").is_file() {
return Vec::new();
@@ -454,7 +454,7 @@ fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Lib
// ------------------------------------------------------------------ jdk
fn jdk_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
// Java modules without a build manifest carry `.classpath` / `.project` /
// `.idea` instead; a configured JDK or declared source roots mark one too.
let files = match manifests(root, JAVA_MANIFESTS) {
@@ -731,7 +731,7 @@ pub(crate) fn gradle_jar(home: &Path, d: &BuildDependency) -> Option<PathBuf> {
// ------------------------------------------------------------------ node
fn node_groups(root: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn node_groups(root: &Path, _project: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
if !root.join("package.json").is_file() {
return Vec::new();
}
@@ -907,7 +907,7 @@ pub(crate) fn parse_cargo_metadata(json: &str) -> Option<Vec<(String, PathBuf)>>
// ------------------------------------------------------------------ go
fn go_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn go_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(mut files) = manifests(root, GO_MANIFESTS) else { return Vec::new() };
if !root.join("go.mod").is_file() && !root.join("go.work").is_file() {
return Vec::new();
@@ -958,7 +958,7 @@ fn go_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Libra
} else if let Some(text) =
query_in_cancellable(&go, &["list", "-m", "-e", "-json", "all"], root, &env, GRAPH_TIMEOUT, cancel)
{
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text))));
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text, project))));
}
out
})
@@ -978,8 +978,19 @@ fn vendor_roots(vendor: &Path, text: &str) -> Vec<(String, PathBuf)> {
.collect()
}
/// `(path@version, dir)` of the downloaded non-main modules in `go list -m -json` output.
pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
/// True when `path` is source the user owns: inside `project` and not a `vendor` copy.
fn is_project_source(project: &Path, path: &Path) -> bool {
let project = project.canonicalize().unwrap_or_else(|_| project.to_path_buf());
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let Ok(relative) = path.strip_prefix(&project) else { return false };
!relative.components().any(|component| component.as_os_str() == "vendor")
}
/// `(path@version, dir)` of the modules that are libraries: everything whose source is
/// outside the opened project. Source inside it is the user's own code — the target of a
/// `replace`, say — and stays editable; a `vendor` copy is the exception, checked in and
/// kept read-only.
pub(crate) fn parse_go_modules(text: &str, project: &Path) -> Vec<(String, PathBuf)> {
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Module {
@@ -993,6 +1004,8 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
.into_iter::<Module>()
.map_while(Result::ok)
.filter(|m| !m.main)
// A module whose source sits in the project is the user's own code, not a library.
.filter(|m| m.dir.as_deref().is_none_or(|dir| !is_project_source(project, dir)))
.filter_map(|m| {
let name = match &m.version {
Some(v) => format!("{}@{v}", m.path),
@@ -1005,7 +1018,7 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
// ------------------------------------------------------------------ zig
fn zig_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn zig_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, ZIG_MANIFESTS) else { return Vec::new() };
let Some(zig) = tool(crate::apply::zig_bin(root, s), "zig") else { return Vec::new() };
cached_cancellable(root, "zig", zig.display().to_string(), &files, cancel, || {
@@ -1574,7 +1587,7 @@ mod zig_tests {
std::fs::set_permissions(&zig, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut settings = Settings::default();
settings.languages.zig.zig = "tools".into();
let groups = zig_groups(root, &settings, &CancellationToken::new());
let groups = zig_groups(root, root, &settings, &CancellationToken::new());
let summary: Vec<(&str, &str, Vec<&str>)> = groups
.iter()
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
+30 -1
Переглянути файл
@@ -1875,7 +1875,7 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}
{"Path":"example.com/missing","Version":"v1.0.0","Error":{"Err":"module lookup disabled"}}"#;
assert_eq!(
crate::libraries::parse_go_modules(out),
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
[(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
@@ -1883,6 +1883,35 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
);
}
#[test]
fn go_modules_skip_module_sources_inside_the_project() {
let out = r#"{"Path":"example.com/app","Main":true,"Dir":"/p/app"}
{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}
{"Path":"example.com/vendored","Version":"v0.0.0","Dir":"/p/vendor/vendored"}
{"Path":"example.com/outside","Version":"v1.0.0","Dir":"/other/outside"}
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}"#;
assert_eq!(
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
[
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/p/vendor/vendored")),
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/other/outside")),
(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
),
]
);
// Opened from a root that does not contain it: the same folder is a library again.
assert!(
crate::libraries::parse_go_modules(
r#"{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}"#,
std::path::Path::new("/p/app")
)
.iter()
.any(|(name, _)| name == "example.com/[email protected]")
);
}
#[test]
fn build_zig_zon_dependencies_are_parsed() {
let zon = r#"// the manifest is a Zig struct literal
+1
Переглянути файл
@@ -22,6 +22,7 @@ parking_lot.workspace = true
zip.workspace = true
flate2.workspace = true
tar.workspace = true
rayon.workspace = true
[dev-dependencies]
tempfile.workspace = true
+48 -41
Переглянути файл
@@ -10,6 +10,7 @@ mod rules;
mod watch;
use ide_core::{IdeError, IdeResult};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::cmp::Ordering;
@@ -133,51 +134,57 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
let excludes = ExcludeMatcher::new(excludes);
let mut entries: Vec<(bool, FileEntry)> = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = match entry {
Ok(e) => e,
let paths: Vec<PathBuf> = fs::read_dir(dir)?
.filter_map(|entry| match entry {
Ok(e) => Some(e.path()),
Err(e) => {
tracing::debug!("read_dir {}: {e}", dir.display());
continue;
None
}
};
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let Ok(lmeta) = fs::symlink_metadata(&path) else { continue };
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
match fs::metadata(&path) {
Ok(m) => {
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
(EntryKind::Symlink, m, Some(target))
})
.collect();
// One stat per entry dominates a large folder (and every stat is a round trip on a network
// share): stat in parallel; small folders stay on this thread.
let mut entries: Vec<(bool, FileEntry)> = paths
.into_par_iter()
.with_min_len(256)
.filter_map(|path| {
let name = path.file_name()?.to_string_lossy().into_owned();
let lmeta = fs::symlink_metadata(&path).ok()?;
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
match fs::metadata(&path) {
Ok(m) => {
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
(EntryKind::Symlink, m, Some(target))
}
Err(_) => (EntryKind::Symlink, lmeta, None),
}
Err(_) => (EntryKind::Symlink, lmeta, None),
}
} else if lmeta.is_dir() {
(EntryKind::Dir, lmeta, None)
} else {
(EntryKind::File, lmeta, None)
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
entries.push((
is_dir,
FileEntry {
hidden: name.starts_with('.'),
size: if is_dir { 0 } else { meta.len() },
mtime_ms: mtime_ms(&meta),
name,
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
));
}
entries.sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
} else if lmeta.is_dir() {
(EntryKind::Dir, lmeta, None)
} else {
(EntryKind::File, lmeta, None)
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
Some((
is_dir,
FileEntry {
hidden: name.starts_with('.'),
size: if is_dir { 0 } else { meta.len() },
mtime_ms: mtime_ms(&meta),
name,
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
))
})
.collect();
entries.par_sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
Ok(entries.into_iter().map(|(_, e)| e).collect())
}
+1
Переглянути файл
@@ -850,6 +850,7 @@ mod tests {
"agent": "",
"agentModel": "",
"agentEffort": "",
"agentButton": true,
})
);
}
+1 -1
Переглянути файл
@@ -29,7 +29,7 @@ Conventions:
| ---------- | --------------------------------------- | --------------------------------------------------------------------------------------- |
| oxfmt | `pnpm format` (CI: `pnpm format:check`) | `.oxfmtrc.json`: print width 120, double quotes, semicolons, trailing commas everywhere |
| oxlint | `pnpm lint` | `.oxlintrc.json`: TypeScript and React plugins |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `perf/`, `scripts/`, `smoke/` |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `e2e/`, `evals/`, `perf/`, `scripts/`, `smoke/` |
| knip | `pnpm knip` | `knip.ts`: unused files, exports and dependencies |
`pnpm knip` fails on an export nobody imports, a file nobody reaches or a dependency nobody uses. Delete dead code rather than suppressing it; exports used only inside their own file are allowed.
+4 -2
Переглянути файл
@@ -55,7 +55,9 @@ Codex keeps its own project trust decision. If it disables the current project's
<Step title="Pick the agent and its settings">
Choose the agent, and its model, mode and other options when it offers them. Cached models appear immediately; the selected agent's catalog refreshes in the background when it is more than 15 minutes old, without sending a prompt or attaching project MCP servers.
Model-specific effort levels and context options are looked up when you select a model whose settings are not cached, even before its first task. **Loading model settings…** appears beside the model during this short-lived lookup; no prompt is sent and existing tasks are not changed. Each model keeps its own choices, and models that report no effort control do not borrow another model's levels.
Click the model name to switch models, or click the settings beside it (for example **High · 1M**) to change effort or context size directly. In the model list, use the arrow on a model's row to see its settings without selecting it. Changing a setting selects that model; going back without an edit keeps the previous selection. These controls are also available in an existing chat.
If settings aren't cached, OpenIDEA looks them up when you select or inspect the model. No prompt is sent. Each model keeps its own draft choices, and models that report no effort control do not borrow another model's levels.
After changing the agent CLI or account, open the model picker and choose **Refresh models**. Refreshes share one lookup and have a 30-second cooldown after completion, including failures. Selecting an uncached model's settings does not wait for another model's cooldown. Cached choices remain usable while refreshing or after a failure; use **Refresh models** to retry a failed lookup after its cooldown.
@@ -137,7 +139,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
## Add a custom agent
+1 -1
Переглянути файл
@@ -123,7 +123,7 @@ These commands are in the **Run** menu and on the Debug tool window toolbar.
While the program is suspended:
- The **Variables** view shows the variables of the selected frame. Right-click a value for **Set Value…** (`F2`), **Copy Value**, **Copy Name**, **Jump to Source** (`F4`) and **Add to Watches**.
- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**.
- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**, or all of them with **Remove All Watches**.
- Hovering a variable in the editor shows its value. `⌥`-click (`Alt`-click) or **Quick Evaluate Expression** (`⌘⌥F8` / `Ctrl+Alt+F8`) evaluates the expression under the mouse or the selection.
- Values of local variables are shown inline after the lines that use them.
- **Evaluate Expression…** (`⌥F8` / `Alt+F8`) opens a dialog that evaluates any expression in the selected frame, keeps a history, and can add the expression to watches.
+1 -1
Переглянути файл
@@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st
Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**.
- File paths and stack trace frames in the output are links.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
+1
Переглянути файл
@@ -206,6 +206,7 @@ Limits: interactive rebase doesn't support ranges with merge commits, and **Undo
- **Shelve Changes…** lets you pick files and a name; the changes are then reverted.
- **Unshelve…** applies a shelf (or one file of it) with a three-way merge, into a changelist you choose.
- **Shelve Silently** (`⇧⌘H` / `Ctrl+Shift+H`, also on the Changes toolbar) shelves the selected changes, or the active changelist, without the dialog: one shelf per changelist, named after it. **Unshelve Silently** (`⌥⌘U` / `Ctrl+Alt+U` in the Shelf) applies the selected shelf or file into the changelist with the shelf's name, else the active one.
- The **Shelf** tab shows shelves with diff, compare with local, patch export, rename and delete.
Turn on **Combine stashes and shelves in one tab** in the Git settings to show both in one tab.
+6 -6
Переглянути файл
@@ -25,12 +25,12 @@ description: "Rust 与 TypeScript 的格式化、lint 和死代码检查,以
## TypeScript 与 React
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、分号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `e2e/`、`evals/`、`perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
`pnpm knip` 发现没人 import 的导出、没人引用的文件或没人用的依赖时会失败。请删掉死代码,而不是屏蔽检查;只在本文件内使用的导出是允许的。
+4 -2
Переглянути файл
@@ -55,7 +55,9 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
<Step title="选择 agent 及其设置">
选择 agent,以及它提供的模型、模式等选项。缓存的模型会立即显示;所选 agent 的模型列表超过 15 分钟未更新时,会在后台刷新,不发送提示词,也不接入项目 MCP 服务器。
选择尚未缓存设置的模型时,会按需查询该模型的思考强度和上下文选项,无需先运行任务。短暂查询期间,模型旁会显示**正在加载模型设置…**;查询不发送提示词,也不更改现有任务。每个模型分别保留你选择的设置;明确不提供思考强度的模型不会沿用其他模型的强度选项。
点击模型名称可切换模型;点击旁边的设置(如 **High · 1M**)可直接调整思考强度或上下文大小。在模型列表中,点击一行右侧的箭头可以先查看该模型的设置。修改设置时才会选中该模型,直接返回则保留原来的选择。在已有对话中也可以这样操作。
选择模型或查看其设置时,如果还没有缓存,OpenIDEA 会按需查询,无需发送提示词。草稿分别保留各模型的选择;未提供思考强度的模型不会沿用其他模型的选项。
更改 agent CLI 或账号后,打开模型选择器并单击 **刷新模型**。并发刷新会共用一次查询;每次查询完成后(包括失败)都有 30 秒冷却时间。查询其他未缓存模型的设置无需等待前一个模型的冷却时间。刷新中或刷新失败后,缓存选项仍可使用;查询失败后,可在冷却结束后用**刷新模型**重试。
@@ -137,7 +139,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
## 添加自定义 agent
+1 -1
Переглянути файл
@@ -125,7 +125,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
程序挂起时:
- **变量** 视图显示选中帧的变量。右键点击某个值,可以 **设置值…**(`F2`)、**复制值**、**复制名称**、**跳转到源代码**(`F4`)和 **添加到监视**。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除,用 **移除所有监视** 一次全部删除。
- 在编辑器里悬停变量会显示它的值。`⌥` 点击(`Alt` 点击)或 **快速计算表达式**(`⌘⌥F8` / `Ctrl+Alt+F8`)计算鼠标下的表达式或选中的内容。
- 局部变量的值会内联显示在使用它们的行尾。
- **计算表达式…**(`⌥F8` / `Alt+F8`)打开对话框,在选中帧里计算任意表达式,带历史记录,也能把表达式加入监视。
+1 -1
Переглянути файл
@@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。
- 输出里的文件路径和堆栈帧都可以点击跳转。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
+1
Переглянути файл
@@ -204,6 +204,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
- **搁置更改…**:选择文件并命名,之后这些更改会被还原。
- **取消搁置…**:以三方合并的方式把搁置(或其中某个文件)应用到你选择的更改列表。
- **静默搁置**(`⇧⌘H` / `Ctrl+Shift+H`,也在更改工具栏上)不弹对话框,直接搁置选中的更改(未选中时为活动更改列表):每个更改列表一个搁置,以列表名命名。**静默取消搁置**(在搁置中按 `⌥⌘U` / `Ctrl+Alt+U`)把选中的搁置或文件应用到与搁置同名的更改列表,没有则应用到活动更改列表。
- **搁置** 标签页列出所有搁置,支持查看差异、与本地比较、导出补丁、重命名和删除。
在 Git 设置中打开 **在同一个标签页中合并显示贮藏和搁置**,两者会显示在同一个标签页里。
+50 -6
Переглянути файл
@@ -109,6 +109,7 @@ async function seed(
model = "atlas",
status: AgentTask["status"] = "ready",
catalogOnly = false,
offered = provider,
) {
await stubDesktop(page);
await page.evaluate(
@@ -218,7 +219,7 @@ async function seed(
if (surface === "new") store.openHome();
else store.openTask(firstTask.id);
},
{ placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId, catalogOnly },
{ placement, surface, provider: offered, firstTask, secondTask, subagent, model, status, modelId, catalogOnly },
);
await expect(box(page)).toBeVisible();
await page.evaluate(() => document.fonts.ready);
@@ -233,9 +234,8 @@ function history(page: Page) {
function modelButton(page: Page) {
return page.getByRole("button", { name: "Model", exact: true }).filter({ visible: true });
}
/** The effort is shown on the model button, after the model's name. */
function effortLabel(page: Page) {
return modelButton(page).locator("[class*='modelDetail']");
return page.getByRole("button", { name: /^Model settings:/ }).filter({ visible: true });
}
async function expectEffort(page: Page, name: string) {
await expect(effortLabel(page)).toHaveText(name);
@@ -284,6 +284,50 @@ async function expectNoSubmission(page: Page) {
expect(await ipcCalls(page, "agent_create")).toEqual([]);
}
for (const surface of ["new", "task"] as const) {
test(`${surface}: configure another model from its row, then edit its context from the composer`, async ({
workbench: page,
}) => {
const context = option(
"context_tier",
"model_config",
[
["default", "200K"],
["long_context", "1M"],
],
"default",
);
const offered = {
...provider,
thoughtLevels: { ...provider.thoughtLevels, atlas: [atlas, context], swift: [swift, context] },
};
await seed(page, "editor", surface, "atlas", "ready", false, offered);
await box(page).fill("Review the project structure");
await modelButton(page).click();
const row = page.getByRole("option", { name: /^Swift\b/ });
await row.hover();
const configure = row.getByRole("button", { name: "Configure Swift…" });
if (surface === "task") await configure.press("Enter");
else await configure.click();
await expect(modelButton(page)).toHaveText("Atlas");
await expect(page.getByRole("radio", { name: "Gentle" })).toHaveCount(0);
await page.getByRole("radio", { name: "Thorough" }).click();
await expect(modelButton(page)).toHaveText("Swift");
await expect(page.getByRole("radio", { name: "Thorough" })).toBeChecked();
await page.keyboard.press("Escape");
const settings = page.getByRole("button", { name: /^Model settings:/ });
await expect(settings).toHaveText("Thorough · 200K");
await settings.click();
await page.getByRole("radio", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.getByRole("button", { name: "Back to models" }).click();
await expect(page.getByRole("listbox", { name: "Model", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
await expectNoSubmission(page);
});
}
for (const placement of ["editor", "toolWindow"] as const) {
test(`${placement}: existing task cycles advertised values and wraps without editing, moving focus or scrolling`, async ({
workbench: page,
@@ -379,7 +423,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toBeFocused();
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await modelButton(page).click();
await effortLabel(page).click();
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
@@ -603,7 +647,7 @@ test("New Task discovers uncached model effort before the first prompt", async (
await page.screenshot({ path: testInfo.outputPath("model-settings-loading.png") });
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await modelButton(page).click();
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
@@ -636,7 +680,7 @@ test("an existing chat can choose effort for a refreshed model before sending",
await expect(loading).toHaveCount(0);
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
await expectEffort(page, "Quick");
await modelButton(page).click();
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@ const firstTask: AgentTask = {
const secondTask: AgentTask = { ...firstTask, id: "focus-second", title: "Second focus task" };
const draft = "draft keep this unsent";
const reboundShortcut = "Control+Meta+Shift+J";
const subagent: AgentEntry = {
const subagent: Extract<AgentEntry, { type: "subagent" }> = {
type: "subagent",
id: "focus-child",
title: "Inspect focus behavior",
+1 -1
Переглянути файл
@@ -149,7 +149,7 @@ test("opens slash-prefixed Windows Markdown links with preview content and hover
for (const [label, path, heading] of [
["Specification", spec, "Windows specification"],
["Work skill", skill, "Work specification skill"],
]) {
] as const) {
const link = reply.getByRole("link", { name: label, exact: true });
await link.hover();
await expect(link).toHaveAttribute("title", path);
+7 -7
Переглянути файл
@@ -1,5 +1,7 @@
import { expect, test } from "./fixtures";
import type { AgentQuestion, AgentTask } from "../src/bindings";
import type * as AgentStore from "../src/features/agents/store";
import type * as Ipc from "../src/platform/ipc";
const task: AgentTask = {
id: "questions",
@@ -49,14 +51,12 @@ for (const status of ["running", "ready"] as const) {
const key = JSON.stringify(["request_user_input_async", "call-1", 0]);
await page.evaluate(
async ({ task, status, key }) => {
// Keep the workbench imports in the browser's Vite realm.
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
(await import(ipcPath)).commands.agentAnswerQuestion = async (
id: string,
question: string,
answer: string | null,
) => {
const store: typeof AgentStore = await import(storePath);
const { commands }: typeof Ipc = await import(ipcPath);
commands.agentAnswerQuestion = async (id, question, answer) => {
document.documentElement.dataset.asyncAnswer = JSON.stringify({ id, question, answer });
const entries = store.useAgents.getState().entries.get(id)!;
store.useAgents.setState({
@@ -111,7 +111,7 @@ for (const status of ["running", "ready"] as const) {
if (status === "running") {
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
const { useAgents }: typeof AgentStore = await import(storePath);
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set(id, { ...s.tasks.get(id)!, status: "ready" }) }));
}, task.id);
await expect(card.getByRole("radio", { name: /^Read latest content/ })).toBeChecked();
+7 -4
Переглянути файл
@@ -1,3 +1,4 @@
import type * as ProjectStore from "../src/platform/project";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
@@ -114,9 +115,11 @@ test("restricting an attached folder leaves the current project untouched", asyn
test("restricted attachments can be trusted individually from the banner", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const m = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ m);
// Load the running workbench's store in the browser.
const projectPath = "/src/platform/project.ts";
const { useProject }: typeof ProjectStore = await import(/* @vite-ignore */ projectPath);
const primary = useProject.getState().project;
if (!primary) throw new Error("Expected the sample project to be open");
let current = {
...primary,
trusted: false,
@@ -126,11 +129,11 @@ test("restricted attachments can be trusted individually from the banner", async
const trusted = new Set([primary.root]);
window.__ipc.handlers.project_trust_status = ({ path }) => ({
root: path,
trusted: trusted.has(path),
trusted: typeof path === "string" && trusted.has(path),
decided: true,
});
window.__ipc.handlers.project_trust_set = ({ path, trusted: allow }) => {
if (allow) trusted.add(path);
if (allow && typeof path === "string") trusted.add(path);
current = { ...current, trusted: current.workspace.projects.every((path) => trusted.has(path)) };
};
window.__ipc.handlers.project_current = () => current;
+61
Переглянути файл
@@ -0,0 +1,61 @@
import { expect, test } from "./fixtures";
test("line bookmarks keep their code or description readable in the dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 880, height: 640 });
const name = "QuarterlySettlementReconciliationCoordinator.ts";
const path = `/dev/acme-api/${name}`;
const code = "reconcileCheckoutOrders();";
const description = "Review settlement totals";
await page.evaluate(
async ({ path, code }) => {
const backendModule = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
docBackend().files.set(path, [...Array(27).fill("// Settlement rules"), code, "verifyTotals();", ""].join("\n"));
const services = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ services);
await editorService().openFile(path);
},
{ path, code },
);
await expect(page.locator(".cm-content")).toContainText(code);
await page.evaluate(
async ({ path, description }) => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("navigate.toggleBookmark", { path, line: 27 });
await executeAction("navigate.toggleBookmark", { path, line: 29 });
const bookmarkModule = "/src/features/search/bookmarks/store.ts";
const { assignMnemonic, updateBookmarks } = await import(/* @vite-ignore */ bookmarkModule);
updateBookmarks((items: unknown[]) => assignMnemonic(items, path, 28, "verifyTotals();", "4", description));
await executeAction("toolwindow.bookmarks");
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
setToolWindowSize("left", 240);
},
{ path, description },
);
const tree = page.getByRole("tree", { name: "Bookmarks" });
await expect(tree.getByText(name, { exact: true })).toBeVisible();
const snippet = tree.getByText(code, { exact: true });
await expect.poll(() => snippet.evaluate((el) => el.clientWidth)).toBeGreaterThanOrEqual(105);
await expect(tree.getByText("28:", { exact: true })).toBeVisible();
await expect(tree.getByText("29:", { exact: true })).toBeVisible();
await expect(tree.getByText(description, { exact: true })).toBeVisible();
await expect(tree.getByText("(empty line)", { exact: true })).toBeVisible();
expect(await tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
const row = tree.getByRole("treeitem").filter({ hasText: code });
await row.click();
await page.keyboard.press("Enter");
await expect
.poll(() =>
page.evaluate(async () => {
const module = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ module);
const cursor = editorService().activeCursor();
return { path: cursor?.path, line: cursor?.line };
}),
)
.toEqual({ path, line: 27 });
});
+71
Переглянути файл
@@ -0,0 +1,71 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Branch comparison keeps both commit ranges and the diff action visible", async ({ workbench: page }) => {
const branch = "feature/settlement-reconciliation-and-international-ledger-reporting";
const current = "feature/review-quarterly-settlement-audit";
const incomingSubject = "Keep regional settlement references stable during the report export";
const outgoingSubject = "Preserve the audit trail for settlement retries";
await page.setViewportSize({ width: 1120, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ branch, current, incomingSubject, outgoingSubject }) => {
const root = "/dev/acme-api";
const branchInfo = {
head: current,
headCommit: "b".repeat(40),
upstream: null,
ahead: 0,
behind: 0,
operation: null,
};
const entry = (letter: string, summary: string) => ({
id: letter.repeat(40),
shortId: letter.repeat(8),
parents: ["a".repeat(40)],
refs: [],
summary,
message: summary + "\n\nUpdate the audit report context.",
author: "Sam Rivera",
email: "[email protected]",
timeMs: 1795100000000,
});
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, ...branchInfo }];
h.vcs_branch_info = () => branchInfo;
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { range: string }).range === `HEAD..${branch}`
? [entry("c", incomingSubject)]
: [entry("b", outgoingSubject)];
h.window_open_comparison = () => null;
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo });
const path = "/src/features/vcs/CompareBranches.tsx";
(await import(/* @vite-ignore */ path)).showCompareBranches(branch);
},
{ branch, current, incomingSubject, outgoingSubject },
);
const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) });
await expect(dialog.getByRole("listbox")).toHaveCount(2);
const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` });
const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` });
await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible();
await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible();
const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const start = (await divider.boundingBox())!.y;
await divider.focus();
await page.keyboard.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1);
await page.setViewportSize({ width: 440, height: 660 });
const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) });
await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(incoming.getByRole("option")).toBeVisible();
await expect(outgoing.getByRole("option")).toBeVisible();
await dialog.getByRole("button", { name: "Show Diff", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "window_open_comparison"))
.toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]);
});
+50
Переглянути файл
@@ -0,0 +1,50 @@
import { expect, test } from "./fixtures";
test("keeps breakpoint details editable when the dialog gets narrow", async ({ workbench: page }) => {
await page.setViewportSize({ width: 500, height: 480 });
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const storeModule = "/src/features/debugger/breakpoints/store.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
const { addBreakpoint } = await import(/* @vite-ignore */ storeModule);
addBreakpoint("/dev/acme-api/CheckInternationalSettlementBeforeDispatch.java", 7, {
condition: "amount > 100",
});
addBreakpoint("/dev/acme-api/Receipt.java", 4);
await executeAction("debug.viewBreakpoints");
});
const dialog = page.getByRole("dialog", { name: "Breakpoints" });
const list = dialog.getByRole("listbox", { name: "All breakpoints" });
const condition = dialog.locator('input[aria-label="Condition"]');
await expect(condition).toHaveValue("amount > 100");
await expect.poll(async () => (await condition.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(240);
await expect(dialog.getByRole("button", { name: "Done", exact: true })).toBeInViewport({ ratio: 1 });
await condition.fill("amount > 250");
await dialog.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check();
await dialog.getByRole("textbox", { name: "Evaluate and log", exact: true }).fill("total: {amount}");
const first = list.getByRole("option", { name: /CheckInternationalSettlementBeforeDispatch\.java:8/ });
await expect(first.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 });
await list.getByRole("option", { name: /Receipt\.java:5/ }).click();
await expect(condition).toHaveValue("");
await first.click();
await expect(condition).toHaveValue("amount > 250");
await expect(dialog.getByRole("textbox", { name: "Evaluate and log", exact: true })).toHaveValue("total: {amount}");
await page.setViewportSize({ width: 1080, height: 760 });
const divider = dialog.locator('[data-separator][aria-orientation="vertical"]');
await expect(divider).toBeInViewport();
const oldWidth = (await list.boundingBox())!.width;
const handle = (await divider.boundingBox())!;
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + 60, handle.y + handle.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(async () => (await list.boundingBox())?.width ?? 0).toBeGreaterThan(oldWidth + 20);
await expect(condition).toHaveValue("amount > 250");
const request = dialog.getByRole("textbox", { name: "Part of a request URL" });
await request.scrollIntoViewIfNeeded();
await expect(request).toBeInViewport({ ratio: 1 });
await dialog.getByRole("button", { name: "Done", exact: true }).click();
await expect(dialog).toBeHidden();
});
+75
Переглянути файл
@@ -0,0 +1,75 @@
import type { MethodSignature } from "../src/bindings";
import { expect, stubDesktop, test } from "./fixtures";
const signature: MethodSignature = {
methodIdentifier: "invoice",
modifier: "",
returnType: "Invoice",
methodName: "prepareInvoiceForInternationalSettlement",
parameters: [
["Order", "order"],
["String", "billingCurrency"],
["BigDecimal", "amountBeforeDiscount"],
["Map<String, BigDecimal>", "taxRatesByJurisdiction"],
["List<Adjustment>", "settlementAdjustments"],
["RoundingMode", "roundingMode"],
["LocalDate", "scheduledSettlementDate"],
["boolean", "includeTaxBreakdown"],
].map(([type, name], originalIndex) => ({ type: type!, name: name!, originalIndex, defaultValue: "" })),
exceptions: [],
};
test("keeps parameter rows and a long signature preview usable in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 490, height: 520 });
await page.evaluate(async () => {
const workbench = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ workbench);
await editorService().openFile("/dev/acme-api/InvoiceService.java");
});
const editor = page.locator(".cm-editor .cm-content");
await expect(editor).toBeVisible();
await stubDesktop(page);
const fontSize = await editor.evaluate(async (content, signature) => {
window.__ipc.handlers.lsp_signature_info = () => signature;
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const prefsModule = "/src/editor/core/cm/prefs.ts";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
const base = Number.parseFloat(getComputedStyle(content).fontSize);
const view = EditorView.findFromDOM(content as HTMLElement)!;
stepFontZoom(view, 4);
view.focus();
return `${base + 4}px`;
}, signature);
await expect(editor).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Meta+F6");
const dialog = page.getByRole("dialog", { name: "Change Signature" });
const table = dialog.getByRole("table", { name: "Parameters" });
const names = table.getByRole("textbox", { name: "Name", exact: true });
await expect(names.first()).toBeInViewport({ ratio: 1 });
const defaults = table.getByRole("columnheader", { name: "Default value", exact: true });
await expect(defaults).toHaveCount(0);
const preview = dialog.locator("pre");
await expect(preview).toBeInViewport({ ratio: 1 });
await expect(preview).toHaveCSS("font-size", fontSize);
await expect(names.first()).toHaveCSS("font-size", fontSize);
expect(
await preview.evaluate((el) => el.scrollHeight > el.clientHeight && el.scrollWidth <= el.clientWidth + 1),
).toBe(true);
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport({ ratio: 1 });
await dialog.getByRole("button", { name: "Add", exact: true }).click();
await expect(defaults).toBeInViewport({ ratio: 1 });
const addedType = table.getByRole("textbox", { name: "Type", exact: true }).last();
await expect(addedType).toBeInViewport({ ratio: 1 });
await addedType.fill("boolean");
await names.last().fill("attachReceipt");
await table.getByRole("textbox", { name: "Default value", exact: true }).last().fill("false");
await dialog.getByRole("button", { name: "Move Up", exact: true }).click();
await expect(names.nth(7)).toHaveValue("attachReceipt");
await expect(preview).toContainText("boolean attachReceipt");
await expect(dialog.getByRole("button", { name: "Preview", exact: true })).toBeEnabled();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const REPO = "https://example.test/team/billing-service.git";
test("Clone Repository keeps URL, directory, and depth usable when the dialog narrows", async ({ workbench: page }) => {
await stubDesktop(page);
await page.setViewportSize({ width: 440, height: 620 });
await page.evaluate(async (repo) => {
window.__ipc.handlers["plugin:dialog|open"] = () => "/dev/workspaces";
window.__ipc.handlers.vcs_clone = () => new Promise(() => {});
const contributionsPath = "/src/workbench/contributions.ts";
const { registerCloneSource } = await import(/* @vite-ignore */ contributionsPath);
registerCloneSource({ id: "team", label: "Team repositories", icon: "branch", component: () => null });
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("vcs.clone", repo);
}, REPO);
const dialog = page.getByRole("dialog", { name: "Clone Repository" });
const sources = dialog.getByRole("complementary", { name: "Clone source" });
const url = dialog.getByRole("textbox", { name: "URL:" });
await expect(url).toHaveValue(REPO);
await expect.poll(async () => (await url.boundingBox())!.width).toBeGreaterThan(180);
const form = dialog.locator("form");
const position = () =>
form.evaluate((el) => {
const source = el.parentElement!.querySelector("aside")!.getBoundingClientRect();
const body = el.getBoundingClientRect();
return { below: body.top >= source.bottom, beside: body.left >= source.right };
});
await expect.poll(async () => (await position()).below).toBe(true);
expect(await form.evaluate((el) => el.scrollWidth === el.clientWidth)).toBe(true);
await dialog.getByRole("button", { name: "Browse…" }).click();
const directory = dialog.getByRole("textbox", { name: "Directory:" });
await expect(directory).toHaveValue("/dev/workspaces/billing-service");
const shallow = dialog.getByRole("checkbox", { name: /^Shallow clone/ });
const depth = dialog.getByRole("spinbutton", { name: "Clone depth" });
await expect(depth).toBeDisabled();
await shallow.check();
await depth.fill("0");
const clone = dialog.getByRole("button", { name: "Clone", exact: true });
await expect(clone).toBeDisabled();
await depth.fill("3");
await page.setViewportSize({ width: 1050, height: 750 });
await expect.poll(async () => (await position()).beside).toBe(true);
await sources.getByRole("button", { name: "Team repositories" }).click();
await expect(url).toBeHidden();
await sources.getByRole("button", { name: "Repository URL" }).click();
await expect(url).toHaveValue(REPO);
await expect(directory).toHaveValue("/dev/workspaces/billing-service");
await expect(depth).toHaveValue("3");
await page.setViewportSize({ width: 440, height: 620 });
await clone.click();
await expect
.poll(() => ipcCalls(page, "vcs_clone"))
.toEqual([expect.objectContaining({ url: REPO, dest: "/dev/workspaces/billing-service", depth: 3 })]);
});
+1 -1
Переглянути файл
@@ -559,7 +559,7 @@ test("indexed single-file rename previews all anchors and applies only after con
}
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
const [apply] = await ipcCalls(page, "apply_workspace_edit");
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
expect(apply?.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({
+53
Переглянути файл
@@ -0,0 +1,53 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Code Style keeps settings reachable by tab, keyboard, and search in a narrow pane", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 620, height: 720 });
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await stubDesktop(page);
await page.evaluate(async () => {
window.__ipc.handlers.languages = () => [
{ id: "typescript", name: "TypeScript", indent: { tabSize: 2, insertSpaces: true }, lineComment: "//" },
];
const languageList = "/src/platform/languageList.ts";
(await import(/* @vite-ignore */ languageList)).languageListChanged();
});
const search = dialog.getByRole("textbox", { name: "Search settings" });
await search.fill("typescript");
await dialog.getByRole("treeitem", { name: "TypeScript", exact: true, level: 3 }).click();
await search.clear();
const tabs = dialog.getByRole("tablist", { name: "Code Style" });
const indents = tabs.getByRole("tab", { name: "Tabs and Indents" });
const wrapping = tabs.getByRole("tab", { name: "Wrapping", exact: true });
const comments = tabs.getByRole("tab", { name: "Comment Code" });
await expect(indents).toHaveAttribute("aria-selected", "true");
const size = dialog.getByRole("textbox", { name: "Tab size", exact: true });
const indent = dialog.getByRole("textbox", { name: "Indent", exact: true });
await expect(indent).toBeVisible();
expect((await indent.boundingBox())!.x).toBeCloseTo((await size.boundingBox())!.x, 0);
await size.fill("6");
await indents.press("ArrowRight");
await expect(wrapping).toBeFocused();
await expect(dialog.getByRole("textbox", { name: "Hard wrap at", exact: true })).toBeVisible();
await expect(size).toBeHidden();
await search.fill("TypeScript line comment at first column");
await expect(comments).toHaveAttribute("aria-selected", "true");
await expect(dialog.getByRole("checkbox", { name: "Line comment at first column" })).toBeVisible();
await indents.click();
await expect(size).toHaveValue("6");
await page.setViewportSize({ width: 520, height: 720 });
const body = dialog.locator("[class*='pageBody']");
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(dialog.getByRole("button", { name: "Copy to Project", exact: true })).toBeVisible();
await search.fill("do not format");
await dialog.getByRole("treeitem", { name: "Code Style", exact: true, level: 2 }).click();
await expect(dialog.getByRole("tab", { name: "Formatter", exact: true })).toHaveAttribute("aria-selected", "true");
await expect(dialog.getByRole("listbox", { name: "Do not format" })).toBeVisible();
});
+40
Переглянути файл
@@ -0,0 +1,40 @@
import { expect, test } from "./fixtures";
test("Color Scheme keeps the preview visible while editing an attribute in narrow Settings", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Language Defaults");
await settings.getByRole("treeitem", { name: "Language Defaults", exact: true }).click();
await search.clear();
const divider = settings.getByRole("separator", { name: "Resize color scheme preview", exact: true });
const tree = settings.getByRole("tree", { name: "Color scheme attributes", exact: true });
const options = settings.getByRole("region", { name: "Color scheme options", exact: true });
const preview = settings.getByLabel("Color scheme preview", { exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
expect((await tree.boundingBox())!.x).toBeLessThan((await options.boundingBox())!.x);
await page.setViewportSize({ width: 520, height: 660 });
await expect.poll(async () => (await tree.boundingBox())!.y).toBeLessThan((await options.boundingBox())!.y);
const previewTop = (await preview.boundingBox())!.y;
const token = preview.getByText("class", { exact: true }).first();
await token.click();
await expect(tree.getByRole("treeitem", { name: "Keyword", exact: true, selected: true })).toBeVisible();
await options.getByRole("textbox", { name: "Foreground hex", exact: true }).fill("#118899");
await expect(token).toHaveCSS("color", "rgb(17, 136, 153)");
await expect(preview).toBeInViewport();
expect((await preview.boundingBox())!.y).toBeCloseTo(previewTop, 0);
await expect
.poll(() => settings.locator("[class*='pageBody']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
await options.getByRole("checkbox", { name: "Semantic highlighting" }).scrollIntoViewIfNeeded();
expect((await preview.boundingBox())!.y).toBeCloseTo(previewTop, 0);
const before = (await divider.boundingBox())!.y;
await divider.press("ArrowUp");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeLessThan(before - 1);
});
+2 -2
Переглянути файл
@@ -6,7 +6,7 @@ for (const [id, selector] of [
["keymap", "[class*='presetLabel']"],
["editor.inspections", "[class*='profileRow'] > span:first-child"],
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
]) {
] as const) {
test(`${id} keeps compact labels inside their controls`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog");
@@ -41,7 +41,7 @@ for (const [id, selector] of [
for (const [id, selector] of [
["general", "[class*='fontRow'] > label"],
["build.console", "[class*='inlineRow'] > label"],
]) {
] as const) {
test(`${id} keeps a readable width for inline text`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
await expect(page.getByRole("dialog", { name: "Settings", exact: true })).toBeVisible();
+1 -1
Переглянути файл
@@ -49,7 +49,7 @@ commands.lspHover = async () => {
};
commands.lspDocumentLinks = async () => ({ status: "ok", data: [] });
commands.lspDocumentHighlights = async () => ({ status: "ok", data: [] });
commands.cancelRequest = async () => ({ status: "ok", data: null });
commands.cancelRequest = async () => {};
const java = new EditorView({
parent: javaHost,
state: EditorState.create({
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@ test("data source tabs share a stable layout and scroll within a short window",
const dialog = page.getByRole("dialog", { name: "New Data Source" });
const panel = dialog.getByRole("tabpanel");
const dialogSize = () => dialog.evaluate((element) => [element.offsetWidth, element.offsetHeight]);
const dialogSize = () => dialog.evaluate((element: HTMLElement) => [element.offsetWidth, element.offsetHeight]);
await expect(panel.getByRole("textbox", { name: "Host:" })).toBeVisible();
const size = await dialogSize();
await dialog.getByRole("tab", { name: "SSH/SSL" }).click();
+1 -1
Переглянути файл
@@ -187,7 +187,7 @@ test("result context menu fits the viewport, responds to hover and keyboard, and
for (const [theme, label] of [
["solarized-light", "Solarized Light"],
["solarized-dark", "Solarized Dark"],
]) {
] as const) {
test(`${label}: retains the inactive context-menu target's hover until dismissal without selecting it`, async ({
workbench: page,
}, info) => {
+57
Переглянути файл
@@ -113,3 +113,60 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
await expect.poll(() => ipcCalls(page, "debug_resume")).toHaveLength(1);
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
});
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 580, height: 420 });
await stubDesktop(page);
await page.evaluate(async (session) => {
const handlers = window.__ipc.handlers;
handlers.debug_capabilities = () => ({});
handlers.debug_completions = () => [];
handlers.debug_evaluate_in = () => ({
name: "orderSummary",
typeName: "OrderSummary",
value: "total = 36",
variablesReference: 210,
evaluateName: null,
});
handlers.debug_variables = () => [
{ name: "tax", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
];
const stateModule = "/src/features/debugger/state.ts";
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
adoptSession(session, { name: "Checkout", adapter: "debugpy", status: "paused", selectedFrame: 11 });
}, SESSION);
await page.keyboard.press("Alt+F8");
const dialog = page.getByRole("dialog", { name: "Evaluate expression" });
const field = dialog.getByRole("textbox", { name: "Expression" });
const expression = ["orderSummary(", ...Array.from({ length: 12 }, (_, i) => ` item${i},`), ")"].join("\n");
await field.fill(expression);
await field.press("Enter");
const result = dialog.getByRole("tree", { name: "Evaluation result" });
const row = result.getByRole("treeitem").first();
await expect(row).toContainText("total = 36");
await expect
.poll(() =>
dialog.locator("[data-dialog-body]").evaluate((body) => {
const area = body.querySelector("textarea")!;
const resultRow = body.querySelector('[role="treeitem"]')!.getBoundingClientRect();
const bounds = body.getBoundingClientRect();
return (
body.scrollHeight <= body.clientHeight + 1 &&
area.scrollHeight > area.clientHeight &&
resultRow.top >= bounds.top &&
resultRow.bottom <= bounds.bottom
);
}),
)
.toBe(true);
await row.click();
await row.press("ArrowRight");
await expect(result.getByText("tax", { exact: true })).toBeVisible();
await field.fill("otherExpression");
await dialog.getByRole("button", { name: "History", exact: true }).click();
await page.getByRole("menuitem", { name: /orderSummary/ }).click();
await expect(field).toHaveValue(expression);
await expect(field).toBeFocused();
});
+75
Переглянути файл
@@ -0,0 +1,75 @@
import { expect, stubDesktop, test } from "./fixtures";
const functionName = "calculateRegionalSettlementFromExternalOrderBeforeReconciliation";
const sourcePath = "/dev/acme-api/build.gradle.kts";
test("keeps frame sources and the keyboard selection visible in a narrow debug dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 540 });
await stubDesktop(page);
await page.evaluate(
async ({ functionName, sourcePath }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const workerFrame = {
id: 51,
name: "processOrder",
path: sourcePath,
line: 5,
column: 0,
presentationHint: null,
};
window.__ipc.handlers.debug_scopes = () => [];
window.__ipc.handlers.debug_stack_trace = () => [workerFrame];
adoptSession(91, {
name: "Reconciliation",
adapter: "debugpy",
status: "paused",
stoppedThread: 1,
selectedThread: 1,
threads: [
{ id: 1, name: "MainThread" },
{ id: 2, name: "Order worker" },
],
selectedFrame: 1,
frames: Array.from({ length: 32 }, (_, index) => ({
id: index + 1,
name: index === 0 ? functionName : index === 1 ? "runBatch" : `reconcile(${index})`,
path: sourcePath,
line: index === 0 ? 41 : index,
column: 0,
presentationHint: null,
})),
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 420);
toolWindowService().show("debug", true);
},
{ functionName, sourcePath },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const thread = debug.getByRole("button", { name: "Thread", exact: true });
const frames = debug.getByRole("listbox", { name: "Frames", exact: true });
const first = frames.getByRole("option", { selected: true });
await expect(first.getByText(functionName, { exact: true })).toBeVisible();
expect(await frames.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(first.getByText(":42", { exact: true })).toBeInViewport({ ratio: 1 });
expect(await first.getByText(/build\.gradle\.kts/).evaluate((el) => el.clientWidth)).toBeGreaterThan(25);
const shortName = frames.getByText("runBatch", { exact: true });
expect(await shortName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await frames.focus();
for (let i = 0; i < 25; i++) await page.keyboard.press("ArrowDown");
const selected = frames.getByRole("option", { selected: true });
await expect(selected.getByText("reconcile(25)", { exact: true })).toBeInViewport({ ratio: 0.95 });
expect(await frames.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await thread.click();
await page.getByRole("option", { name: "Order worker", exact: true }).click();
await expect(thread).toContainText("Order worker");
await expect(frames.getByRole("option", { selected: true })).toContainText("processOrder");
});
+63
Переглянути файл
@@ -0,0 +1,63 @@
import { expect, stubDesktop, test } from "./fixtures";
const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding";
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
const routingValue = "'APR-2026 / eu-west / batch-701 / settlement complete'";
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const h = window.__ipc.handlers;
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
];
adoptSession(91, {
name: "Checkout",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingValue, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await page.setViewportSize({ width: 1640, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
});
await expect(show).toBeHidden();
await expect
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
});
+54
Переглянути файл
@@ -232,6 +232,48 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
});
test("the inline find and replace controls stay inside a narrow editor pane", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const editor = await openFromTree(page, "build.gradle.kts");
await editor.locator(".cm-content").click();
await page.keyboard.press("Meta+r");
const bar = page.getByRole("search", { name: "Replace in file" });
const find = bar.getByRole("textbox", { name: "Find" });
const replace = bar.getByRole("textbox", { name: "Replace" });
const next = bar.getByRole("button", { name: /Next Occurrence/ });
await find.fill("OrderDto");
await find.press("Tab");
await expect(replace).toBeFocused();
await replace.fill("OrderView");
const navigationIsBelowFind = async () => {
const [input, button] = await Promise.all([find.boundingBox(), next.boundingBox()]);
return !!input && !!button && button.y >= input.y + input.height;
};
const controlsFit = () =>
bar.evaluate((panel) => {
const bounds = panel.getBoundingClientRect();
return [...panel.querySelectorAll("button, textarea")].every((element) => {
const control = element.getBoundingClientRect();
return control.width > 0 && control.left >= bounds.left && control.right <= bounds.right;
});
});
await expect.poll(navigationIsBelowFind).toBe(false);
await page.setViewportSize({ width: 590, height: 760 });
await expect.poll(controlsFit).toBe(true);
await expect.poll(navigationIsBelowFind).toBe(true);
await page.setViewportSize({ width: 495, height: 760 });
await expect.poll(controlsFit).toBe(true);
await expect(find).toHaveValue("OrderDto");
await expect(replace).toHaveValue("OrderView");
await next.click();
await expect(bar.getByText(/^[12]\/2$/)).toBeVisible();
await bar.getByRole("button", { name: "Replace All" }).click();
await expect(editor.locator(".cm-line", { hasText: "OrderView" })).toHaveCount(2);
await bar.getByRole("button", { name: "Close", exact: true }).click();
await expect(bar).toBeHidden();
});
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
workbench: page,
}) => {
@@ -596,3 +638,15 @@ test("dragging the Markdown split divider resizes and reflows editor and preview
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
.toBe(Math.round(initialEditor));
});
test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await page.getByRole("button", { name: "Preview Only" }).click();
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true });
// A hidden editor panel used to leave an implicit resize region over everything left of the preview,
// which swallowed the click.
await row.click();
await expect(row).toHaveAttribute("aria-selected", "true");
});
+42
Переглянути файл
@@ -0,0 +1,42 @@
import { expect, test } from "./fixtures";
test("Editor Font keeps the preview in view while editing and resizing the controls", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1200, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Show only monospaced fonts");
await settings.getByRole("treeitem", { name: "Font", exact: true, level: 2 }).click();
await search.clear();
const divider = settings.getByRole("separator", { name: "Resize font preview" });
const options = settings.getByRole("region", { name: "Font options", exact: true });
const preview = settings.getByRole("textbox", { name: "Font preview", exact: true });
const font = options.getByRole("combobox", { name: "Font", exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
expect((await font.boundingBox())!.x).toBeLessThan((await preview.boundingBox())!.x);
await expect.poll(() => preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await preview.fill("function main() { return 42; }");
await options.getByRole("textbox", { name: "Size", exact: true }).fill("18");
await options.getByRole("textbox", { name: "Line height", exact: true }).fill("25");
await expect(preview).toHaveCSS("font-size", "18px");
await expect(preview).toHaveCSS("line-height", "25px");
await page.setViewportSize({ width: 520, height: 620 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
expect((await font.boundingBox())!.y).toBeLessThan((await preview.boundingBox())!.y);
await expect(preview).toHaveValue("function main() { return 42; }");
const y = (await divider.boundingBox())!.y;
await divider.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(y + 1);
await search.fill("Fallback font");
const fallback = options.getByRole("combobox", { name: "Fallback font", exact: true });
await fallback.scrollIntoViewIfNeeded();
await expect(fallback).toBeInViewport();
await fallback.fill("Consolas");
await expect(preview).toHaveCSS("font-family", /Consolas/);
await expect(preview).toBeInViewport();
await expect.poll(() => options.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
+12
Переглянути файл
@@ -64,3 +64,15 @@ test("editor Git submenu keeps repository actions disabled without Git", async (
}
await expect(page.getByRole("menuitem", { name: "Clone…", exact: true })).toBeEnabled();
});
test("Project view Git submenu ends with Manage Remotes and Clone", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: /README\.md/ }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
const git = page.getByRole("menu").filter({ has: page.getByRole("menuitem", { name: "Clone…", exact: true }) });
const items = git.locator('[role="menuitem"], [role="menuitemcheckbox"]');
await expect(items.nth(-3)).toHaveText(/Unstash Changes…/);
await expect(items.nth(-2)).toHaveText(/Manage Remotes…/);
await expect(items.nth(-1)).toHaveText(/Clone…/);
await git.getByRole("menuitem", { name: "Manage Remotes…", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Git Remotes" })).toBeVisible();
});
+90
Переглянути файл
@@ -0,0 +1,90 @@
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, test } from "./fixtures";
async function setTabs(page: Page, tabs: Record<string, unknown>) {
await page.evaluate(async (tabs) => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { settings } = useProject.getState();
useProject.setState({
settings: { ...settings, editor: { ...settings?.editor, tabs: { ...settings?.editor?.tabs, ...tabs } } },
});
}, tabs);
}
const box = async (locator: Locator) => (await locator.boundingBox())!;
const closeOf = (tab: Locator) => tab.locator("..").getByRole("button", { name: "Close Tab", exact: true });
test("a close button on the right keeps a narrow slot on every tab", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "build.gradle.kts");
const strip = page.getByRole("tablist", { name: "Editor tabs" });
const idle = strip.getByRole("tab", { name: "README.md" });
const label = await box(idle.locator(":scope > span"));
const idleTab = await box(idle.locator(".."));
expect(idleTab.x + idleTab.width - (label.x + label.width)).toBeCloseTo(18, 0);
const selected = strip.getByRole("tab", { name: "build.gradle.kts" });
const close = await box(closeOf(selected));
const tab = await box(selected.locator(".."));
const text = await box(selected.locator(":scope > span"));
expect(close.x).toBeGreaterThanOrEqual(text.x + text.width - 0.5);
expect(close.x + close.width).toBeLessThanOrEqual(tab.x + tab.width + 0.5);
expect(tab.x - (idleTab.x + idleTab.width)).toBeCloseTo(4, 0);
});
for (const closeButtonPosition of ["right", "left"]) {
test(`a dragged tab's ghost keeps the tab's layout, close button ${closeButtonPosition}`, async ({
workbench: page,
}) => {
await openFromTree(page, "README.md");
await openFromTree(page, "build.gradle.kts");
await setTabs(page, { closeButtonPosition });
const selected = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "build.gradle.kts" });
const tab = await box(selected.locator(".."));
const close = await box(closeOf(selected));
await page.mouse.move(tab.x + tab.width / 2, tab.y + tab.height / 2);
await page.mouse.down();
await page.mouse.move(tab.x + tab.width / 2, tab.y + tab.height / 2 + 40, { steps: 4 });
const ghost = page.locator('[aria-hidden="true"]:has([data-tab-close])');
const copy = await box(ghost);
const copyClose = await box(ghost.locator("[data-tab-close] button"));
expect(copy.width).toBeCloseTo(tab.width, 0);
expect(copyClose.x - copy.x).toBeCloseTo(close.x - tab.x, 0);
expect(copyClose.x + copyClose.width).toBeLessThanOrEqual(copy.x + copy.width + 0.5);
await page.keyboard.press("Escape");
await page.mouse.up();
await expect(ghost).toHaveCount(0);
});
}
test("a close button on the left keeps a narrow slot before the icon", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "build.gradle.kts");
await setTabs(page, { closeButtonPosition: "left" });
const strip = page.getByRole("tablist", { name: "Editor tabs" });
// The selected and the hovered tab show their button in an 18px slot before the icon, which stays visible.
const selected = strip.getByRole("tab", { name: "build.gradle.kts" });
const other = strip.getByRole("tab", { name: "README.md" });
await other.hover();
for (const tab of [selected, other]) {
const icon = tab.locator(":scope > :first-child");
await expect(icon).toHaveCSS("opacity", "1");
await expect(closeOf(tab)).toHaveCSS("opacity", "1");
const slot = await box(tab.locator(".."));
const close = await box(closeOf(tab));
const glyph = await box(icon);
const label = await box(tab.locator(":scope > span"));
expect(close.x + close.width).toBeLessThanOrEqual(glyph.x + 0.5);
expect(glyph.x - slot.x).toBeCloseTo(18, 0);
expect(slot.x + slot.width - (label.x + label.width)).toBeCloseTo(8, 0);
}
// Without file icons the close button keeps its own place before the label.
await setTabs(page, { showFileIcon: false });
await expect(selected.locator("svg, img")).toHaveCount(0);
const label = await box(selected.locator(":scope > span"));
const slot = await box(closeOf(selected));
expect(slot.x + slot.width).toBeLessThanOrEqual(label.x + 0.5);
});
+86
Переглянути файл
@@ -0,0 +1,86 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const root = "/dev/acme-api";
const name = `InternationalSettlement${"Reconciliation".repeat(10)}.txt`;
const destination = `archive/Approved${"Settlement".repeat(11)}`;
test("keeps a long source name and destination readable while moving a file", async ({ workbench: page }) => {
await page.evaluate(
async ({ root, name, destination }) => {
const fsModule = "/src/features/project-tree/fs.ts";
const { projectFs } = await import(/* @vite-ignore */ fsModule);
const storeModule = "/src/features/project-tree/store.ts";
const { loadDir } = await import(/* @vite-ignore */ storeModule);
const fs = projectFs(root);
await fs.createFile(`${root}/${name}`);
await fs.createDir(`${root}/archive`);
await fs.createDir(`${root}/${destination}`);
await loadDir(root, true);
},
{ root, name, destination },
);
await page.getByRole("treeitem", { name, exact: true }).click();
await page.keyboard.press("F6");
const dialog = page.getByRole("dialog", { name: "Move", exact: true });
const field = dialog.getByRole("textbox", { name: "Target directory" });
await expect(field).toBeFocused();
await page.setViewportSize({ width: 470, height: 480 });
await expect
.poll(() => dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
expect(
await field.evaluate((el: HTMLInputElement) => el.value.slice(el.selectionStart ?? 0, el.selectionEnd ?? 0)),
).toBe("acme-api");
const submit = dialog.getByRole("button", { name: "Refactor", exact: true });
await expect(submit).toBeDisabled();
await field.fill(destination);
await expect(dialog.getByText(destination, { exact: true })).toBeVisible();
await expect(submit).toBeInViewport({ ratio: 1 });
await dialog.getByRole("checkbox", { name: "Search for references" }).uncheck();
await dialog.getByRole("checkbox", { name: "Search in comments and strings" }).uncheck();
await submit.click();
await expect(dialog).toBeHidden();
await expect
.poll(() =>
page.evaluate(
async ({ root, destination }) => {
const fsModule = "/src/features/project-tree/fs.ts";
const { projectFs } = await import(/* @vite-ignore */ fsModule);
return (await projectFs(root).readDir(`${root}/${destination}`)).map((entry: { name: string }) => entry.name);
},
{ root, destination },
),
)
.toEqual([name]);
});
test("browses for a destination and keeps the current path on cancel", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.file_dialog_needs_gtk = () => false;
let chosen: string | null = null;
window.__ipc.handlers["plugin:dialog|open"] = () => {
const result = chosen;
chosen = "C:\\Projects\\Invoice Archive";
return result;
};
});
await page.keyboard.press("F6");
const dialog = page.getByRole("dialog", { name: "Move", exact: true });
const field = dialog.getByRole("textbox", { name: "Target directory" });
const browse = dialog.getByRole("button", { name: "Browse for target directory", exact: true });
await browse.click();
await expect.poll(() => ipcCalls(page, "plugin:dialog|open")).toHaveLength(1);
await expect(field).toHaveValue(root);
await browse.click();
await expect(field).toHaveValue("C:/Projects/Invoice Archive");
await expect(dialog.getByRole("button", { name: "Refactor", exact: true })).toBeEnabled();
await field.fill("C:/");
await expect(dialog.getByText("C:/", { exact: true })).toBeVisible();
await field.fill("/");
await expect(dialog.getByText("/", { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { expect, stubDesktop, test } from "./fixtures";
test("File Types keeps association editors usable and opens ignored rules from search", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settings).toBeVisible();
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.languages = () => [
{ id: "javascript", name: "JavaScript", extensions: ["js"] },
{ id: "python", name: "Python", extensions: ["py", "pyi", "pyw"], filenames: ["SConstruct", "SConscript"] },
];
});
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("File Types");
await settings.getByRole("treeitem", { name: "File Types", exact: true }).click();
await search.clear();
const tabs = settings.getByRole("tablist", { name: "File Types" });
const recognized = tabs.getByRole("tab", { name: "Recognized File Types" });
const ignored = tabs.getByRole("tab", { name: "Ignored Files and Folders" });
await expect(recognized).toHaveAttribute("aria-selected", "true");
const divider = settings.getByRole("separator", { name: "Resize file type panes" });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await page.setViewportSize({ width: 520, height: 660 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const types = settings.getByRole("listbox", { name: "Recognized file types", exact: true });
await types.getByRole("option", { name: "Python", exact: true }).click();
const patterns = settings.getByRole("listbox", { name: "File name patterns of Python" });
const hashbangLabel = settings.getByText("Hashbang patterns", { exact: true });
await expect
.poll(async () => {
const nameList = await patterns.boundingBox();
const hashbangHeading = await hashbangLabel.boundingBox();
return nameList && hashbangHeading ? hashbangHeading.y - (nameList.y + nameList.height) : -1;
})
.toBeGreaterThan(0);
await expect
.poll(() => settings.locator("[class*='_patterns_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
const toolbar = settings.locator(`[role="toolbar"][aria-controls="${await patterns.getAttribute("id")}"]`);
await toolbar.getByRole("button", { name: "Add" }).click();
const pattern = patterns.getByRole("textbox", { name: "Pattern" });
await pattern.fill("*.layout-demo");
await pattern.press("Enter");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
await expect
.poll(() => settings.locator("[class*='pageBody']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
await search.fill("Exclude patterns");
await expect(ignored).toHaveAttribute("aria-selected", "true");
await expect(settings.getByRole("listbox", { name: "Exclude patterns" })).toBeVisible();
await expect(patterns).toBeHidden();
await ignored.click();
await search.clear();
await ignored.press("ArrowLeft");
await expect(recognized).toHaveAttribute("aria-selected", "true");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
});
+98
Переглянути файл
@@ -0,0 +1,98 @@
import type { EditorView } from "@codemirror/view";
import { expect, stubDesktop, test } from "./fixtures";
test("Hierarchy keeps source context and controls reachable in a narrow dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 940, height: 680 });
const path = "/dev/acme-api/QuarterlySettlementReconciliationCoordinator.ts";
const caller = "reconcileQuarterlySettlementForMerchantOrders";
const context = "Checkout and settlement coordinator";
await page.evaluate(
async ({ path, caller }) => {
const backend = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backend);
docBackend().files.set(
path,
[
"function settleOrder() {}",
"",
`function ${caller}() {`,
" settleOrder();",
" settleOrder();",
"}",
`function flushSettlementQueue() { ${caller}(); }`,
].join("\n"),
);
const service = "/src/workbench/contributions.ts";
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
},
{ path, caller },
);
const editor = page.locator(".cm-content");
await expect(editor).toContainText("settleOrder");
await editor.evaluate((el) => {
const view = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
view.dispatch({ selection: { anchor: 11 } });
view.focus();
});
await stubDesktop(page);
await page.evaluate(
async ({ path, caller, context }) => {
const range = (line: number, col: number) => ({ start: { line, col }, end: { line, col: col + 5 } });
const item = (name: string, line: number, detail: string, fromRanges: ReturnType<typeof range>[]) => ({
name,
path,
detail,
kind: "function",
range: range(line, 0),
selectionRange: range(line, 9),
fromRanges,
});
window.__ipc.handlers.lsp_call_hierarchy = ({ pos }) => {
const line = (pos as { line: number }).line;
return {
items:
line === 0
? [item(caller, 2, context, [range(3, 2), range(4, 2)])]
: [item("flushSettlementQueue", 6, "Queue processing", [range(6, 34)])],
incomplete: null,
};
};
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.callHierarchy");
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("right", 136);
},
{ path, caller, context },
);
const tree = page.getByRole("tree", { name: "Call hierarchy" });
const row = tree.getByRole("treeitem").filter({ hasText: caller });
await expect(row).toBeVisible();
const detail = row.getByText(context, { exact: true });
await expect.poll(() => detail.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
expect((await row.getByText("(2 calls)", { exact: true }).boundingBox())!.x).toBeLessThan(
(await detail.boundingBox())!.x,
);
const toolbar = page.getByRole("toolbar", { name: "Hierarchy actions" });
expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await tree.evaluate((el) => {
el.scrollLeft = el.scrollWidth;
});
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(100);
await tree.evaluate((el) => {
el.scrollLeft = 0;
});
await row.click({ position: { x: 90, y: 12 } });
await page.keyboard.press("ArrowRight");
await expect(tree.getByRole("treeitem").filter({ hasText: "flushSettlementQueue" })).toBeVisible();
await page.keyboard.press("Enter");
await expect
.poll(() =>
page.evaluate(async () => {
const service = "/src/workbench/contributions.ts";
const cursor = (await import(/* @vite-ignore */ service)).editorService().activeCursor();
return { path: cursor?.path, line: cursor?.line, col: cursor?.col };
}),
)
.toEqual({ path, line: 3, col: 2 });
});
+3 -4
Переглянути файл
@@ -45,11 +45,10 @@ POST https://example.test/messages
const json = document.createElement("div");
json.id = "json";
document.body.append(json);
const jsonSupport = await loadSupport(findLanguageDescription("JSON", "body.json")!);
if (!jsonSupport) throw new Error("Failed to load JSON support for the highlighting fixture");
new EditorView({
parent: json,
doc: '{"name": "World", "count": 12, "enabled": true, "ready": false, "empty": null, "items": [1]}',
extensions: [
await loadSupport(findLanguageDescription("JSON", "body.json")!),
syntaxHighlighting(openideaHighlightStyle),
],
extensions: [jsonSupport, syntaxHighlighting(openideaHighlightStyle)],
});
+7 -4
Переглянути файл
@@ -1,4 +1,5 @@
import { readFileSync } from "node:fs";
import type * as EditorBackend from "../src/editor/core/backend";
import { expect, test } from "./fixtures";
const xml = readFileSync(
@@ -10,13 +11,14 @@ test("imported PHP colours stay separate from Java and preserve regular text on
workbench: page,
}, info) => {
await page.evaluate(async (xml) => {
// Load the workbench modules in the browser's Vite realm.
const iclsPath = "/src/platform/icls.ts";
const projectPath = "/src/platform/project.ts";
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { parseIcls } = await import(iclsPath);
const { useProject } = await import(projectPath);
const { docBackend } = await import(backendPath);
const { docBackend }: typeof EditorBackend = await import(backendPath);
const { editorService } = await import(contributionsPath);
const previous = useProject.getState().settings ?? {};
useProject.setState({
@@ -31,10 +33,11 @@ test("imported PHP colours stay separate from Java and preserve regular text on
},
});
const backend = docBackend();
if (!("files" in backend) || !(backend.files instanceof Map)) throw new Error("Expected the in-memory backend");
const open = backend.open.bind(backend);
backend.open = async (...args: Parameters<typeof open>) => {
const result = await open(...args);
return args[0].endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
backend.open = async (path) => {
const result = await open(path);
return path.endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
};
backend.files.set(
"/dev/acme-api/palette.php",
+2 -1
Переглянути файл
@@ -1,5 +1,6 @@
import { EditorView } from "@codemirror/view";
import { commands, type InlayHint, type Range } from "../src/platform/ipc";
import type { InlayHint, Range } from "../src/bindings";
import { commands } from "../src/platform/ipc";
import { setInvokeRoute } from "../src/platform/tauriCore";
import { lspDoc } from "../src/editor/lsp/lsp";
import { inlayExtension } from "../src/editor/lsp/inlay";
+52
Переглянути файл
@@ -0,0 +1,52 @@
import { expect, test } from "./fixtures";
test("Inspections keeps the selected rule and its controls usable as the pane changes width", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 620, height: 720 });
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await page.evaluate(async () => {
const path = "/src/features/settings/model/staging.ts";
(await import(/* @vite-ignore */ path)).selectPage("editor.inspections");
});
const search = dialog.getByRole("textbox", { name: "Search inspections" });
await search.fill("typo");
const tree = dialog.getByRole("tree", { name: "Inspections" });
const typo = tree.getByRole("treeitem", { name: /Typo/ });
await typo.click();
const body = dialog.locator("[class*='pageBody']");
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const resize = dialog.getByRole("separator", { name: "Resize inspection panes" });
const details = dialog.getByRole("region", { name: "Inspection details" });
await expect(resize).toHaveAttribute("aria-orientation", "horizontal");
await expect(details.getByRole("heading", { name: "Typo" })).toBeVisible();
const narrowTree = await tree.boundingBox();
const narrowDetails = await details.boundingBox();
expect(narrowDetails!.y).toBeGreaterThan(narrowTree!.y + narrowTree!.height);
await expect(details.getByRole("separator", { name: "Resize inspection description" })).toHaveAttribute(
"aria-orientation",
"horizontal",
);
const severity = details.getByRole("button", { name: "Severity" });
const severityBox = await severity.boundingBox();
expect(severityBox!.y + severityBox!.height).toBeLessThan(narrowDetails!.y + narrowDetails!.height);
await severity.click();
await page.getByRole("option", { name: "Warning", exact: true }).click();
const code = details.getByRole("checkbox", { name: "Process code" });
await code.uncheck();
await expect(severity).toHaveText("Warning");
await page.setViewportSize({ width: 1040, height: 740 });
await expect(resize).toHaveAttribute("aria-orientation", "vertical");
const width = (await tree.boundingBox())!.width;
await resize.press("ArrowRight");
await expect.poll(async () => (await tree.boundingBox())!.width).toBeGreaterThan(width + 5);
await expect(typo).toHaveAttribute("aria-selected", "true");
await expect(severity).toHaveText("Warning");
await expect(code).not.toBeChecked();
});
+90
Переглянути файл
@@ -0,0 +1,90 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Interactive rebase keeps commit messages and plan controls usable at narrow widths", async ({
workbench: page,
}) => {
const first = "Keep regional settlement references stable when reconciling delayed ledger updates";
const second = "Add settlement summary";
await stubDesktop(page);
await page.evaluate(
async ({ first, second }) => {
const root = "/dev/acme-api";
const id = (n: string) => n.repeat(40);
const commits = [
{ id: id("c"), shortId: "cccccccc", parents: [id("b")], summary: second, timeMs: 1795100200000 },
{ id: id("b"), shortId: "bbbbbbbb", parents: [id("a")], summary: first, timeMs: 1795100100000 },
].map((commit) => ({
...commit,
refs: [],
author: "Sam Rivera",
email: "[email protected]",
message: commit.summary + "\n\nKeep the audit trail linked to the settlement job.",
}));
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: id("c") }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: id("c"),
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_log = () => commits;
h.vcs_log_refs = () => ({});
h.vcs_log_users = () => ["Sam Rivera <[email protected]>"];
h.vcs_config_get = () => null;
h.vcs_commit_files = () => [];
h.vcs_log_details_batch = () => [];
const vcsPath = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ vcsPath);
useVcs.setState({ available: true, root, roots: [root], repo: root, branchesLoaded: true });
const contextPath = "/src/platform/context.ts";
(await import(/* @vite-ignore */ contextPath)).setContext("vcsAvailable", true);
const actionsPath = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actionsPath)).executeAction("vcs.showLog");
},
{ first, second },
);
const log = page.getByRole("listbox", { name: "Commits" });
await log.getByRole("option", { name: new RegExp(first) }).click({ button: "right" });
await page.getByRole("menuitem", { name: /Interactively Rebase from Here/ }).click();
const dialog = page.getByRole("dialog", { name: /Rebasing 2 commits/ });
await expect(dialog).toBeVisible();
await page.setViewportSize({ width: 440, height: 640 });
const list = dialog.getByRole("list", { name: "Commits to rebase" });
const originalRows = list.getByRole("listitem");
await dialog.getByRole("button", { name: "Action for bbbbbbbb" }).click();
await page.getByRole("option", { name: "Reword", exact: true }).click();
const reword = dialog.getByRole("textbox", { name: "New message for bbbbbbbb" });
await expect(reword).toHaveValue(first + "\n\nKeep the audit trail linked to the settlement job.");
const editor = (await reword.boundingBox())!;
expect(editor.width).toBeGreaterThan(260);
expect(editor.height).toBeGreaterThan(160);
const divider = dialog.getByRole("separator", { name: "Resize rebase panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const start = dialog.getByRole("button", { name: "Start Rebasing" });
await expect(start).toBeDisabled();
const message = "Keep settlement references stable\n\nPreserve the audit trail.";
await reword.fill(message);
await expect(start).toBeEnabled();
await dialog.getByRole("button", { name: "Move Down" }).click();
await expect(originalRows.first()).toContainText(second);
await expect(reword).toHaveValue(message);
await originalRows
.first()
.getByRole("button", { name: new RegExp(second) })
.click();
const details = dialog.getByRole("region", { name: "Commit details" });
await expect(details).toContainText("Keep the audit trail linked to the settlement job.");
await page.setViewportSize({ width: 1120, height: 760 });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(details).toContainText(second);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(dialog).toBeHidden();
});
+16 -11
Переглянути файл
@@ -1,3 +1,4 @@
import type { DataSource_Deserialize, DbJdbcDriver } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("configures a local JDBC profile and a source through mocked IPC", async ({ workbench: page }, info) => {
@@ -102,21 +103,25 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
await source.getByLabel("Property value", { exact: true }).fill("true");
await test.click();
await expect(source.getByRole("status")).toHaveText("Succeeded: Mock JDBC database");
const [{ source: tested, password }] = await ipcCalls(page, "db_test");
expect(password).toBe("mock secret");
const [tested] = await ipcCalls(page, "db_test");
expect(tested).toMatchObject({
driver: "jdbc",
url,
user: "example-user",
readOnly: true,
properties: [{ name: "ssl", value: "true" }],
password: "mock secret",
source: {
driver: "jdbc",
url,
user: "example-user",
readOnly: true,
properties: [{ name: "ssl", value: "true" }],
},
});
await source.getByRole("button", { name: "OK", exact: true }).click();
await expect(source).not.toBeVisible();
const [{ sources }] = await ipcCalls(page, "db_save_sources");
const [saved] = sources as Record<string, unknown>[];
const [{ driver }] = await ipcCalls(page, "db_save_jdbc_driver");
const [save] = await ipcCalls(page, "db_save_sources");
const saved = (save?.sources as DataSource_Deserialize[] | undefined)?.[0];
const [profile] = await ipcCalls(page, "db_save_jdbc_driver");
const driver = profile?.driver as DbJdbcDriver | undefined;
if (!saved || !driver) throw new Error("Expected the JDBC source and driver to be saved");
expect(saved.readOnly).toBe(true);
expect(saved.jdbcDriver).toBe((driver as Record<string, unknown>).id);
expect(saved.jdbcDriver).toBe(driver.id);
for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key);
});
+56
Переглянути файл
@@ -0,0 +1,56 @@
import { expect, test } from "./fixtures";
test("Keymap fits a narrow Settings pane and keeps shortcut editing reachable", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1080, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
const search = settings.getByRole("textbox", { name: "Search actions" });
const expand = settings.getByRole("button", { name: "Expand All", exact: true });
await expect(search).toBeVisible();
const wideSearch = (await search.boundingBox())!;
const wideExpand = (await expand.boundingBox())!;
expect(wideExpand.x).toBeLessThan(wideSearch.x);
expect(Math.abs(wideExpand.y - wideSearch.y)).toBeLessThan(8);
await page.setViewportSize({ width: 520, height: 760 });
const narrowSearch = (await search.boundingBox())!;
const narrowExpand = (await expand.boundingBox())!;
expect(narrowSearch.y).toBeGreaterThan(narrowExpand.y + narrowExpand.height);
const body = settings.locator("[class*='pageBody']");
const fitPane = () =>
expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await fitPane();
await search.fill("Reformat Code");
const tree = settings.getByRole("tree", { name: "Actions", exact: true });
const action = tree
.getByRole("treeitem")
.filter({ hasText: /Reformat Code/ })
.first();
await action.click();
await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click();
const recorder = page.getByRole("dialog", { name: /Keyboard Shortcut: Reformat Code/ });
await recorder.getByRole("textbox", { name: "First stroke" }).press("Control+Alt+Shift+F8");
await expect(recorder.getByText("No conflicts")).toBeVisible();
await recorder.getByRole("button", { name: "OK", exact: true }).click();
await expect(action.locator("kbd").filter({ hasText: "F8" })).toHaveCount(1);
const title = action.getByText(/Reformat Code/).first();
await expect.poll(() => title.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await tree.evaluate((el) => {
el.scrollLeft = el.scrollWidth;
});
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(0);
await fitPane();
await settings.getByRole("button", { name: "Find Actions by Shortcut" }).click();
await settings.getByRole("textbox", { name: "Find actions by shortcut" }).press("Control+Alt+Shift+F8");
await expect(action).toBeVisible();
await fitPane();
await settings.getByRole("button", { name: "Apply", exact: true }).click();
await expect(settings.getByRole("button", { name: "Apply", exact: true })).toBeDisabled();
});
+3 -3
Переглянути файл
@@ -1,5 +1,5 @@
/** Linked Gradle builds use isolated native stubs; no real builds or files are touched. */
import type { GradleModel, RunConfig } from "../src/platform/ipc";
import type { GradleModel, RunConfig_Deserialize } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const build = (dir: string): GradleModel => ({
@@ -46,7 +46,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
};
h["plugin:dialog|open"] = () => ["/dev/acme-api/second/settings.gradle"];
h.run_start = (args) => {
const config = args.config as RunConfig;
const config = args.config as RunConfig_Deserialize;
const id = ++runId;
setTimeout(() => window.__ipc.emit({ type: "runExited", run: id, code: 0 }), 50);
return { id, configId: config.id, name: config.name, pid: 4242 + id, running: true, pty: false };
@@ -89,7 +89,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
await tasks.nth(1).dblclick();
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(2);
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig);
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig_Deserialize);
expect(runs[0]!.id).not.toBe(runs[1]!.id);
for (const [index, dir] of ["first", "second"].entries()) {
expect(runs[index]).toMatchObject({
+50
Переглянути файл
@@ -0,0 +1,50 @@
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("Local History gives the diff room and keeps revision selection across layouts", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1180, height: 700 });
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const file = "/dev/acme-api/build.gradle.kts";
const entries = [
{ id: "after", path: file, timestampMs: 2000, label: "Saved", size: 31, kind: "snapshot" },
{ id: "before", path: file, timestampMs: 1000, label: "Original", size: 34, kind: "snapshot" },
];
window.__ipc.handlers.history_list_dir = () => ({ entries, deleted: [] });
window.__ipc.handlers.history_content = ({ id }) =>
id === "before" ? 'val reportMode = "summary"\n' : 'val reportMode = "detailed"\n';
window.__ipc.handlers.vcs_file_mode = () => null;
window.__ipc.handlers.fs_probe = () => ({ size: 32, binary: false, tooLarge: false });
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.localHistory", file);
});
const revisions = page.getByRole("listbox", { name: "Revisions" });
await expect(revisions.getByRole("option", { name: /Saved/ })).toBeVisible();
const separator = page.getByRole("separator", { name: "Revisions" });
await expect(separator).toHaveAttribute("aria-orientation", "vertical");
const initialWidth = (await revisions.boundingBox())!.width;
await separator.press("ArrowLeft");
await expect.poll(async () => (await revisions.boundingBox())!.width).toBeLessThan(initialWidth);
const original = revisions.getByRole("option", { name: /^Original/ });
await original.click();
await expect(original).toHaveAttribute("aria-selected", "true");
await expect.poll(async () => ipcCalls(page, "history_content")).toContainEqual({ id: "before" });
await page.setViewportSize({ width: 480, height: 620 });
await expect(separator).toHaveAttribute("aria-orientation", "horizontal");
await expect(original).toHaveAttribute("aria-selected", "true");
const diff = page.locator(".cm-mergeView").filter({ hasText: "summary" });
await expect(diff).toBeVisible();
const listBox = (await revisions.boundingBox())!;
const diffBox = (await diff.boundingBox())!;
expect(diffBox.y).toBeGreaterThanOrEqual(listBox.y + listBox.height);
expect(diffBox.width).toBeGreaterThanOrEqual(listBox.width - 2);
await page.setViewportSize({ width: 1180, height: 700 });
await expect(separator).toHaveAttribute("aria-orientation", "vertical");
await expect(original).toHaveAttribute("aria-selected", "true");
});
+38
Переглянути файл
@@ -63,6 +63,44 @@ const result = (page: Page) => page.getByRole("region", { name: "Result" });
const text = async (pane: Locator) => (await pane.locator(".cm-content").innerText()).replace(/​/g, "");
const status = (page: Page) => page.locator("#merge-host [class*=status]").first();
test("merge controls and pane titles fit while resizing the result", async ({ page }) => {
await page.setViewportSize({ width: 400, height: 600 });
await mountMerge(page);
const host = page.locator("#merge-host");
for (const name of ["Accept Yours", "Accept Theirs", "Cancel", "Apply"])
await expect(host.getByRole("button", { name, exact: true })).toBeInViewport({ ratio: 1 });
await expect(status(page)).toHaveText("3 changes left, 2 conflicts");
await expect(status(page)).toBeInViewport({ ratio: 1 });
const ours = page.getByRole("region", { name: "Your version" });
await expect(ours.getByText("Your version", { exact: true })).toBeVisible();
await expect(
page.getByRole("region", { name: "Their version" }).getByText("Their version", { exact: true }),
).toBeVisible();
await ours.locator(".cm-merge-accept").nth(1).focus();
await page.keyboard.press("Enter");
await expect.poll(() => text(result(page))).toContain("\nmine\n");
await page.setViewportSize({ width: 980, height: 660 });
const resultWidth = async () => (await result(page).boundingBox())!.width;
const initial = await resultWidth();
const left = host.getByRole("separator", { name: "Resize left merge pane" });
await left.press("ArrowLeft");
await expect.poll(resultWidth).toBeGreaterThan(initial + 1);
const right = host.getByRole("separator", { name: "Resize right merge pane" });
const grip = (await right.boundingBox())!;
const withLeftResized = await resultWidth();
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 36, grip.y + grip.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(resultWidth).toBeGreaterThan(withLeftResized + 20);
await expect(result(page).getByText("Result", { exact: true })).toBeVisible();
await expect(ours.getByText("Changes from main", { exact: true })).toBeVisible();
await expect.poll(() => text(result(page))).toContain("\nmine\n");
});
/** Capture the save boundary, keeping real editor state, dialogs and Apply behavior. */
async function captureWrites(page: Page) {
await page.evaluate(async () => {
+110
Переглянути файл
@@ -0,0 +1,110 @@
import type { GeneratorInfo } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const java: GeneratorInfo = {
id: "java",
name: "Java",
group: "Java",
icon: "project-java",
order: 1,
description: "A plain Java application built with Maven or Gradle.",
git: true,
dynamic: false,
fields: [
{
id: "build",
label: "Build system:",
default: "maven",
hint: "",
visible: {},
kind: {
type: "choice",
segmented: true,
options: [
{ value: "maven", label: "Maven" },
{ value: "gradle", label: "Gradle" },
],
},
},
{
id: "jdk",
label: "JDK:",
default: "",
hint: "",
visible: {},
kind: { type: "sdk", sdk: "jdk" },
},
],
};
const empty: GeneratorInfo = {
...java,
id: "empty",
name: "Empty Project",
group: "Project",
description: "",
fields: [],
};
test("New Project fits the template form in a narrow window and preserves edits when resized", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.setViewportSize({ width: 490, height: 570 });
await page.evaluate(
async (catalog) => {
const handlers = window.__ipc.handlers;
handlers.scaffold_catalog = () => catalog;
handlers.sdk_detect = () => [];
handlers.scaffold_requirements = () => [];
handlers.scaffold_create = () => new Promise(() => {});
handlers["plugin:dialog|open"] = () => "/dev/workspaces";
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("file.newProject");
},
[empty, java],
);
const dialog = page.getByRole("dialog", { name: "New Project" });
const generators = dialog.getByRole("listbox", { name: "Generators" });
await generators.getByRole("option", { name: "Java", exact: true }).click();
const form = dialog.locator("form");
const hasNoHorizontalOverflow = (el: Element) => el.scrollWidth === el.clientWidth;
expect(await form.evaluate(hasNoHorizontalOverflow)).toBe(true);
await expect(dialog.getByRole("separator", { name: "Generators" })).toHaveAttribute("aria-orientation", "horizontal");
await dialog.getByRole("textbox", { name: "Name:" }).fill("Billing Service");
await dialog.getByRole("button", { name: "Browse…" }).click();
await expect(dialog.getByRole("textbox", { name: "Location:" })).toHaveValue("/dev/workspaces");
const gradle = dialog.getByRole("button", { name: "Gradle" });
await gradle.click();
await expect(gradle).toHaveAttribute("aria-pressed", "true");
await page.setViewportSize({ width: 1040, height: 750 });
const handle = dialog.getByRole("separator", { name: "Generators" });
await expect(handle).toHaveAttribute("aria-orientation", "vertical");
const originalWidth = (await generators.boundingBox())!.width;
await handle.press("ArrowRight");
await expect.poll(async () => (await generators.boundingBox())!.width).toBeGreaterThan(originalWidth);
await expect(generators.getByRole("option", { name: "Java", exact: true })).toHaveAttribute("aria-selected", "true");
await expect(dialog.getByRole("textbox", { name: "Name:" })).toHaveValue("Billing Service");
await expect(gradle).toHaveAttribute("aria-pressed", "true");
await page.setViewportSize({ width: 490, height: 570 });
await dialog.getByRole("button", { name: "Create", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "scaffold_create"))
.toEqual([
expect.objectContaining({
req: {
generator: "java",
location: "/dev/workspaces",
name: "Billing Service",
git: true,
values: { build: "gradle", jdk: "" },
},
}),
]);
});
+76
Переглянути файл
@@ -0,0 +1,76 @@
import type { Page } from "@playwright/test";
import type { SignatureHelp } from "../src/bindings";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
function signature(name: string, parameters: string[]) {
let offset = name.length + 1;
const ranges: [number, number][] = parameters.map((parameter) => {
const range: [number, number] = [offset, offset + parameter.length];
offset = range[1] + 2;
return range;
});
return { label: `${name}(${parameters.join(", ")}): Invoice`, parameters: ranges, documentation: null };
}
async function openParameterInfo(page: Page, help: SignatureHelp) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((help) => {
window.__ipc.handlers.lsp_signature_help = () => help;
}, help);
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("Meta+p");
const popup = page.locator(".cm-lsp-signature");
await expect(popup).toBeVisible();
return { editor, popup };
}
test("parameter info wraps long parameters and follows the editor width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 700 });
const parameter = "roundingPolicyForThirdPartyPaymentsWithMultipleSettlementCurrencies: RoundingPolicy";
const { editor, popup } = await openParameterInfo(page, {
signatures: [signature("formatInvoice", ["order: Cart", parameter, "currency: string"])],
activeSignature: 0,
activeParameter: 1,
});
await page.setViewportSize({ width: 560, height: 650 });
await expect
.poll(async () => {
const [pane, hint] = await Promise.all([editor.boundingBox(), popup.boundingBox()]);
return !!pane && !!hint && hint.x >= pane.x - 1 && hint.x + hint.width <= pane.x + pane.width + 1;
})
.toBe(true);
await expect.poll(() => popup.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(popup.locator("b")).toHaveText(parameter);
const fontSize = await editor.locator(".cm-content").evaluate((el) => getComputedStyle(el).fontSize);
await expect(popup).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("parameter info keeps the active overload visible and scrolls to the others", async ({ workbench: page }) => {
const signatures = Array.from({ length: 20 }, (_, i) =>
signature("formatInvoice", [`order: Cart${i}`, "currency: string"]),
);
const { popup } = await openParameterInfo(page, { signatures, activeSignature: 16, activeParameter: 1 });
await expect(popup.locator(".cm-lsp-signature-row")).toHaveCount(signatures.length);
const active = popup.locator(".cm-lsp-signature-active b");
await expect(active).toHaveText("currency: string");
await expect
.poll(async () => {
const [frame, parameter] = await Promise.all([popup.boundingBox(), active.boundingBox()]);
return (
!!frame && !!parameter && parameter.y >= frame.y && parameter.y + parameter.height <= frame.y + frame.height
);
})
.toBe(true);
expect(await popup.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await popup.hover();
await page.mouse.wheel(0, -1200);
await expect.poll(() => popup.evaluate((el) => el.scrollTop)).toBe(0);
await expect(
popup.getByText("formatInvoice(order: Cart0, currency: string): Invoice", { exact: true }),
).toBeInViewport();
});
+59
Переглянути файл
@@ -0,0 +1,59 @@
import { expect, openFromTree, test } from "./fixtures";
test("Paste from History keeps the list and preview usable in a short dialog", async ({ workbench: page }) => {
const editor = await openFromTree(page, "App.tsx");
const content = editor.locator(".cm-content");
await content.focus();
const baseFont = Number.parseFloat(await content.evaluate((el) => getComputedStyle(el).fontSize));
await page.evaluate(async () => {
const source = await (await fetch("/src/editor/core/extras.ts")).text();
const imports = [...source.matchAll(/["'](\/src\/[^"']+)["']/g)].map((match) => match[1]!);
const activePath = (path: string) => imports.find((url) => url.split("?")[0] === path) ?? path;
const historyPath = activePath("/src/editor/core/clipboardHistory.ts");
const actionsPath = activePath("/src/platform/actions.ts");
const { recordClipboard } = await import(/* @vite-ignore */ historyPath);
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
recordClipboard("const older = 2;");
recordClipboard("const newest = 1;\n// paste marker");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: async () => {} } });
for (let i = 0; i < 5; i++) await executeAction("editor.increaseFontSize");
});
const fontSize = `${baseFont + 5}px`;
await expect(content).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Meta+Shift+v");
const dialog = page.getByRole("dialog", { name: "Choose Content to Paste" });
const divider = dialog.getByRole("separator", { name: "Resize paste preview" });
const list = dialog.getByRole("listbox", { name: "Clipboard history" });
const preview = dialog.getByLabel("Paste preview", { exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(list.getByText("const newest = 1;", { exact: true })).toHaveCSS("font-size", fontSize);
await expect(preview).toHaveCSS("font-size", fontSize);
await expect(dialog.locator(".cm-gutters")).toHaveCount(0);
await page.setViewportSize({ width: 420, height: 440 });
const search = dialog.getByRole("textbox", { name: "Filter clipboard history" });
const remove = dialog.getByRole("button", { name: "Delete" });
await expect(search).toBeInViewport({ ratio: 1 });
await expect(remove).toBeInViewport({ ratio: 1 });
expect((await remove.boundingBox())!.y).toBeLessThan((await list.boundingBox())!.y);
const previous = Number(await divider.getAttribute("aria-valuenow"));
await divider.press("ArrowDown");
await expect.poll(async () => Number(await divider.getAttribute("aria-valuenow"))).toBeGreaterThan(previous);
const resized = await divider.getAttribute("aria-valuenow");
await expect(dialog.getByRole("button", { name: "Paste" })).toBeInViewport({ ratio: 1 });
await expect(preview).toContainText("// paste marker");
await search.fill("older");
await remove.click();
await expect(dialog.getByText("No matches", { exact: true })).toBeVisible();
await dialog.getByRole("button", { name: "Clear", exact: true }).click();
await expect(search).toHaveValue("");
await search.press("Enter");
await expect(dialog).toBeHidden();
await expect(content).toContainText("const newest = 1;");
await page.keyboard.press("Meta+Shift+v");
await expect(divider).toHaveAttribute("aria-valuenow", resized!);
await page.keyboard.press("Escape");
});
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { expect, test } from "./fixtures";
test("Plugin management keeps the selected details reachable when Settings narrows", async ({ workbench: page }) => {
const name = "ReconciliationTimelineInspectorEnterprise";
const notes = "SettlementTimeline".repeat(18);
await page.evaluate(
async ({ name, notes }) => {
const path = "/src/features/plugins/backend.ts";
const { createMemoryPluginsBackend, setPluginsBackend } = await import(/* @vite-ignore */ path);
const { plugins } = await createMemoryPluginsBackend().list();
const longPlugin = { ...plugins[0], id: "settlement-inspector", name, changeNotes: notes };
setPluginsBackend(createMemoryPluginsBackend([longPlugin, ...plugins.slice(1)]));
},
{ name, notes },
);
await page.setViewportSize({ width: 1080, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Plugins", exact: true }).click();
await settings.getByRole("tab", { name: "Installed", exact: true }).click();
const filter = settings.getByRole("textbox", { name: "Filter plugins" });
const list = settings.getByRole("list", { name: "Installed plugins" });
const details = settings.getByLabel(`${name} details`);
const heading = details.getByRole("heading", { name, exact: true });
await expect(heading).toBeVisible();
const filterBox = (await filter.boundingBox())!;
const headingBox = (await heading.boundingBox())!;
expect(headingBox.x).toBeGreaterThan(filterBox.x + filterBox.width);
await page.setViewportSize({ width: 520, height: 760 });
const body = settings.locator("[class*='pageBody']");
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const divider = settings.getByRole("separator", { name: "Resize plugin panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const sources = settings.getByRole("tablist", { name: "Plugin sources" });
await expect(sources.getByRole("tab", { name: "Marketplace" })).toBeVisible();
await expect(sources.getByRole("tab", { name: "Installed" })).toBeVisible();
expect(await sources.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const before = (await divider.boundingBox())!.y;
await divider.focus();
await page.keyboard.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(before);
await expect(details.getByRole("button", { name: "Disable", exact: true })).toBeVisible();
await details.getByRole("tab", { name: "What's New" }).click();
await expect(details.getByText(notes, { exact: true })).toBeVisible();
expect(await details.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await filter.click();
await expect(filter).toBeFocused();
await filter.pressSequentially("Harbor");
await list.getByRole("button", { name: /Harbor Night Theme/ }).click();
await expect(settings.getByRole("heading", { name: "Harbor Night Theme", exact: true })).toBeVisible();
await page.setViewportSize({ width: 1080, height: 760 });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(filter).toHaveValue("Harbor");
await expect(settings.getByRole("heading", { name: "Harbor Night Theme", exact: true })).toBeVisible();
});
+47
Переглянути файл
@@ -0,0 +1,47 @@
import { expect, stubDesktop, test } from "./fixtures";
const JDK_PATH = "/opt/jdks/corretto-21.0.8";
const LONG_NAME = "AmazonCorretto21".repeat(6);
test("Project Structure SDKs keeps selection and selected details usable in a compact dialog", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.setViewportSize({ width: 520, height: 720 });
await page.evaluate(
async ({ path, name }) => {
const sdk = { path, name, version: "21.0.8", source: "system", home: path, extra: null };
window.__ipc.handlers.sdk_detect = ({ kind }) =>
kind === "jdk"
? [sdk]
: kind === "python"
? [{ ...sdk, path: "/usr/bin/python3", home: "/usr/bin", name: "Python 3.12", version: "3.12.2" }]
: [];
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("file.projectStructure", "sdks");
},
{ path: JDK_PATH, name: LONG_NAME },
);
const dialog = page.getByRole("dialog", { name: "Project Structure" });
const list = dialog.getByRole("listbox", { name: "SDKs" });
const details = dialog.getByRole("region", { name: "SDK Details" });
await expect(list.getByRole("option", { name: /Python 3.12/ })).toBeVisible();
await expect(details.getByText(LONG_NAME, { exact: true })).toBeVisible();
const content = dialog.locator("[class*='psDialogBody']");
expect(await content.evaluate((el) => el.scrollWidth)).toBe(await content.evaluate((el) => el.clientWidth));
const path = details.getByRole("textbox", { name: "SDK home path" });
await expect(path).toHaveValue(JDK_PATH);
await expect(details.getByText("21.0.8", { exact: true })).toBeVisible();
const useSdk = details.getByRole("button", { name: "Use as Project SDK" });
await useSdk.click();
await expect(useSdk).toBeDisabled();
await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeEnabled();
await list.getByRole("option", { name: /Python 3.12/ }).click();
await expect(path).toHaveValue("/usr/bin/python3");
await expect(details.getByText("3.12.2", { exact: true })).toBeVisible();
await expect(useSdk).toHaveCount(0);
});
+86
Переглянути файл
@@ -0,0 +1,86 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Pull fits the remote branch picker and keeps flags accessible in a narrow window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 380, height: 580 });
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/checkout-reconciliation";
const second = `${root}/billing-and-transaction-settlement`;
const branch = {
head: "main",
upstream: "origin/main",
headCommit: "c1",
behind: 1,
ahead: 0,
operation: null,
};
const h = window.__ipc.handlers;
h.vcs_roots = () => [root, second].map((root) => ({ root, ...branch }));
h.vcs_branch_info = () => branch;
h.vcs_status = () => [];
h.vcs_log = () => [];
h.vcs_remotes = () => [
{ name: "origin", url: "/git/checkout-reconciliation.git" },
{ name: "settlement-integration", url: "/git/settlement.git" },
];
h.vcs_branches = () =>
["origin/main", "origin/release/month-end-international-settlement-reconciliation"].map((name) => ({
name,
commit: "c1",
current: false,
remote: true,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
}));
h.vcs_remote = () => new Promise(() => {});
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: second, roots: [root, second], branch });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.pull");
});
const dialog = page.getByRole("dialog", { name: "Pull to main" });
const branch = dialog.getByRole("button", { name: "Remote branch" });
await expect(branch).toHaveText("main");
const body = dialog.locator("[data-dialog-body]");
await expect.poll(() => branch.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThanOrEqual(250);
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
await branch.press("s");
await page.getByRole("option", { name: "release/month-end-international-settlement-reconciliation" }).click();
await expect(branch).toContainText("month-end-international-settlement-reconciliation");
const modify = dialog.getByRole("button", { name: "Modify options" });
await modify.press("Enter");
await page.getByRole("menuitemcheckbox", { name: "--ff-only" }).click();
await expect(dialog.locator("code", { hasText: "--ff-only" })).toBeVisible();
await modify.press("Enter");
await expect(page.getByRole("menuitemcheckbox", { name: "--ff-only" })).toBeChecked();
await expect(page.getByRole("menuitemcheckbox", { name: "--no-commit" })).toBeDisabled();
await page.keyboard.press("Escape");
await expect(modify).toBeFocused();
await dialog.getByRole("button", { name: "Pull", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_remote"))
.toMatchObject([
{
repo: "/dev/checkout-reconciliation/billing-and-transaction-settlement",
op: {
op: "pullFrom",
remote: "origin",
branches: ["release/month-end-international-settlement-reconciliation"],
rebase: false,
options: { ffOnly: true },
},
},
]);
});
+120 -42
Переглянути файл
@@ -9,50 +9,75 @@ import { expect, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const HUGE = `feature/wrap-${"x".repeat(140)}`;
async function openPushDialog(page: Page) {
const OUTGOING = "Apply order-level discounts before calculating checkout taxes";
async function openPushDialog(page: Page, { outgoing = false, multi = false } = {}) {
await stubDesktop(page);
await page.evaluate(async (root) => {
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: "1111111",
upstream: "origin/main",
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_log = () => [];
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
name,
remote,
current: !remote,
upstream,
ahead: 0,
behind: 0,
lastCommitMs: 0,
});
h.vcs_branches = () => [
branch("main", false, "origin/main"),
branch("feature/login", false),
branch("origin/main", true),
branch("origin/feature/login", true),
branch("origin/fix/error-auth", true),
branch("origin/feature/PLATFORM-12345-order-history-export", true),
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
];
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
void executeAction("vcs.push");
}, ROOT);
await page.evaluate(
async ({ root, outgoing, multi, subject }) => {
const h = window.__ipc.handlers;
const head = multi ? "feature/refine-checkout-pricing-and-order-summary-for-regional-release" : "main";
const roots = multi ? [root, `${root}/billing-and-refunds`] : [root];
h.vcs_roots = () => roots.map((root) => ({ root, operation: null, head, headCommit: "1111111" }));
h.vcs_branch_info = () => ({
head,
headCommit: "1111111",
upstream: `origin/${head}`,
ahead: outgoing ? 1 : 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_log = () =>
outgoing
? [
{
id: "2222222",
shortId: "2222222",
parents: ["1111111"],
summary: subject,
message: subject + "\n\nKeep the new totals consistent with receipts.",
author: "Sam Rivera",
email: "[email protected]",
timeMs: 1795100000000,
},
]
: [];
h.vcs_commit_files = () => [{ path: "checkout.ts", oldPath: null, kind: "modified" }];
h.vcs_has_hook = () => false;
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
name,
remote,
current: !remote,
upstream,
ahead: 0,
behind: 0,
lastCommitMs: 0,
});
h.vcs_branches = () => [
branch("main", false, "origin/main"),
branch("feature/login", false),
branch("origin/main", true),
branch("origin/feature/login", true),
branch("origin/fix/error-auth", true),
branch("origin/feature/PLATFORM-12345-order-history-export", true),
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
];
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
void executeAction("vcs.push");
},
{ root: ROOT, outgoing, multi, subject: OUTGOING },
);
const dialog = page.getByRole("dialog", { name: /Push/ });
const input = dialog.getByRole("combobox", { name: "Target branch" });
const input = multi
? dialog.getByRole("textbox", { name: "Target branch of acme-api" })
: dialog.getByRole("combobox", { name: "Target branch" });
await expect(input).toBeVisible();
return { dialog, input };
}
@@ -127,3 +152,56 @@ test("Escape closes the list but keeps the dialog", async ({ workbench: page })
await expect(page.getByRole("listbox", { name: "Remote branches" })).toHaveCount(0);
await expect(dialog).toBeVisible();
});
test("Push keeps commit subjects and changed files readable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1140, height: 760 });
const { dialog, input } = await openPushDialog(page, { outgoing: true });
const outgoing = dialog.getByRole("listbox", { name: "Outgoing commits" });
const files = dialog.getByRole("tree", { name: "Changed files" });
const commit = outgoing.getByRole("option", { name: new RegExp(OUTGOING) });
await commit.click();
await expect(files.getByText("checkout.ts")).toBeVisible();
const filesBelowCommits = async () => {
const [list, tree] = await Promise.all([outgoing.boundingBox(), files.boundingBox()]);
return !!list && !!tree && tree.y >= list.y + list.height;
};
await expect.poll(filesBelowCommits).toBe(false);
await page.setViewportSize({ width: 540, height: 630 });
await expect.poll(filesBelowCommits).toBe(true);
await expect(commit).toHaveAttribute("aria-selected", "true");
const subject = commit.getByText(OUTGOING, { exact: true });
await expect(subject).toHaveAttribute("title", /Sam Rivera/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(input).toHaveValue("main");
await expect(dialog.getByRole("button", { name: "Push", exact: true })).toBeInViewport();
const details = dialog.getByRole("region", { name: "Commit details" });
await expect(details).toContainText("Keep the new totals consistent with receipts.");
await expect
.poll(async () => {
const [tree, message] = await Promise.all([files.boundingBox(), details.boundingBox()]);
return !!tree && !!message && message.y >= tree.y + tree.height;
})
.toBe(true);
});
test("Push keeps per-repository targets editable with long source branches", async ({ workbench: page }) => {
await page.setViewportSize({ width: 475, height: 620 });
const { dialog, input } = await openPushDialog(page, { outgoing: true, multi: true });
const other = dialog.getByRole("textbox", { name: "Target branch of billing-and-refunds" });
for (const field of [input, other]) {
await expect
.poll(() =>
field.evaluate((target) => {
const row = target.closest('[role="treeitem"]')!.getBoundingClientRect();
const bounds = target.getBoundingClientRect();
return bounds.width >= 42 && bounds.left >= row.left && bounds.right <= row.right;
}),
)
.toBe(true);
}
await input.fill("release/checkout");
await expect(input).toHaveValue("release/checkout");
await expect(other).toHaveValue(/^feature\//);
await expect(dialog.getByRole("checkbox", { name: "acme-api" })).toBeChecked();
});
+55
Переглянути файл
@@ -0,0 +1,55 @@
import { expect, openFromTree, test } from "./fixtures";
test("Reformat File aligns scope and option controls and supports arrow-key scope changes", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
await editor.locator(".cm-line").first().click();
await page.keyboard.press("Home");
await page.keyboard.press("Shift+End");
await page.evaluate(async () => {
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("code.reformatDialog");
});
const dialog = page.getByRole("dialog", { name: /Reformat File/ });
const scope = dialog.getByRole("group", { name: "Scope" });
const selected = scope.getByRole("radio", { name: "Selected text" });
await expect(selected).toBeChecked();
await expect(scope.getByRole("radio").first()).toHaveAccessibleName("Selected text");
await selected.press("ArrowDown");
await expect(scope.getByRole("radio", { name: "Whole file" })).toBeChecked();
const optimize = dialog.getByRole("group", { name: "Options" }).getByRole("checkbox", { name: "Optimize imports" });
expect((await selected.boundingBox())!.x).toBeCloseTo((await optimize.boundingBox())!.x, 0);
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
test("Reformat Code keeps long targets and the file mask usable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 340, height: 460 });
const target = "InternationalSettlementReconciliation".repeat(4);
await page.evaluate(async (target) => {
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("code.reformatFiles", { directories: [`/dev/acme-api/${target}`] });
}, target);
const dialog = page.getByRole("dialog", { name: "Reformat Code", exact: true });
await expect(dialog.getByText(target, { exact: true })).toBeVisible();
const body = dialog.locator("[data-dialog-body]");
expect(await body.evaluate((el) => el.scrollWidth)).toBe(await body.evaluate((el) => el.clientWidth));
await expect(
dialog.getByRole("group", { name: "Options" }).getByRole("checkbox", { name: "Include subdirectories" }),
).toBeChecked();
const filters = dialog.getByRole("group", { name: "Filters" });
const mask = filters.getByRole("textbox", { name: "File mask" });
await expect(mask).toBeDisabled();
await filters.getByText("File mask:", { exact: true }).click();
await mask.fill("*.java");
await expect(mask).toHaveValue("*.java");
await dialog.getByRole("button", { name: "Cancel" }).click();
await expect(dialog).toBeHidden();
});
+91 -4
Переглянути файл
@@ -1,3 +1,4 @@
import type { SearchQuery } from "../src/bindings";
import { doubleShift, expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("double Shift opens Search Everywhere with its tabs; Escape closes it", async ({ workbench: page }) => {
@@ -100,11 +101,14 @@ test("Find in Files streams matches by file and opens the chosen one at its line
await expect
.poll(
async () =>
(await ipcCalls(page, "search_start")).filter((c) => !/\bTODO\b/.test(c.query?.pattern ?? "")).at(-1)?.query,
(await ipcCalls(page, "search_start"))
.filter(({ query }) => {
const pattern = query && typeof query === "object" && "pattern" in query ? query.pattern : undefined;
return typeof pattern !== "string" || !/\bTODO\b/.test(pattern);
})
.at(-1)?.query,
)
.toMatchObject({
pattern: "OrderService",
});
.toMatchObject({ pattern: "OrderService" } satisfies Pick<SearchQuery, "pattern">);
const preview = dialog.getByRole("region", { name: "Preview", exact: true }).locator(".cm-content");
await expect(preview).toHaveAttribute("contenteditable", "true");
// Matches take the editor scheme's search result background (IDEA's SEARCH_RESULT_ATTRIBUTES) and keep the syntax colours.
@@ -155,3 +159,86 @@ test("Find in Files streams matches by file and opens the chosen one at its line
}, `Editor for ${ROOT}/build.gradle.kts`);
await expect.poll(caretLine).toBe("import com.acme.orders.service.OrderService");
});
test("the Find tool window keeps the selected preview and replacement actions when narrowed", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1500, height: 820 });
await stubDesktop(page);
await page.evaluate(
({ path, relPath }) => {
window.__ipc.handlers.search_validate = () => null;
window.__ipc.handlers.search_start = ({ query, onEvent }) => {
if ((query as SearchQuery).pattern !== "OrderService") return null;
setTimeout(() => {
window.__ipc.send(onEvent, {
type: "file",
file: {
path,
relPath,
matches: [
{
line: 2,
text: "import com.acme.orders.service.OrderService",
ranges: [[31, 43]],
textOffset: 0,
},
],
},
});
window.__ipc.send(onEvent, {
type: "done",
summary: { files: 1, matches: 1, limitHit: false, cancelled: false, elapsedMs: 1 },
});
}, 20);
return null;
};
},
{ path: `${ROOT}/build.gradle.kts`, relPath: "build.gradle.kts" },
);
await page.keyboard.press("Meta+Shift+r");
const popup = page.getByRole("dialog", { name: "Replace in Files" });
await popup.getByRole("textbox", { name: "Text to find" }).fill("OrderService");
await popup.getByRole("textbox", { name: "Replace with" }).fill("OrdersApi");
await expect(popup.getByRole("listbox", { name: "Matches" }).getByRole("option")).toHaveCount(1);
await popup.getByRole("button", { name: "Open in Find Window", exact: true }).click();
const find = page.getByRole("region", { name: "Find", exact: true });
await find.getByRole("button", { name: "Options", exact: true }).click();
await page.getByRole("menuitem", { name: "Move To", exact: true }).hover();
await page.getByRole("menuitem", { name: "Right Top", exact: true }).click();
const dockDivider = page.getByRole("separator", { name: "Resize right tool window", exact: true });
const resizeDock = async (width: number) => {
await expect(dockDivider).toBeVisible();
const handle = (await dockDivider.boundingBox())!;
const dock = (await find.boundingBox())!;
const x = handle.x + handle.width / 2;
const y = handle.y + handle.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x + dock.width - width, y, { steps: 5 });
await page.mouse.up();
};
await resizeDock(690);
const row = find.getByRole("treeitem", { name: /OrderService.*OrdersApi/ });
await row.click();
const preview = find.getByRole("region", { name: "Preview", exact: true });
await expect(preview.locator(".cm-content")).toContainText("OrderService");
const divider = find.getByRole("separator", { name: "Resize find preview" });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await resizeDock(325);
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(row).toHaveAttribute("aria-selected", "true");
await expect(preview.locator(".cm-content")).toContainText("OrderService");
await expect(find.getByRole("toolbar", { name: "Find actions" })).toHaveAttribute("aria-orientation", "vertical");
for (const label of ["Preview", "Replace Selected", "Replace All"]) {
await expect(find.getByRole("button", { name: label, exact: true })).toBeInViewport({ ratio: 1 });
}
await find.getByRole("button", { name: "Replace All", exact: true }).click();
const confirmation = page.getByRole("dialog", { name: "Replace All" });
await expect(confirmation).toBeVisible();
await confirmation.getByRole("button", { name: "Cancel" }).click();
await expect(confirmation).toBeHidden();
});
+1 -1
Переглянути файл
@@ -79,7 +79,7 @@ test.describe("search popups at the minimum window width", () => {
[400, 500],
[600, 700],
[1120, 750],
]) {
] as const) {
await page.setViewportSize({ width, height });
await expectControlsFit(page);
// Room enough for the title and the reporter's count: shown whole, on one line.
+2 -2
Переглянути файл
@@ -9,9 +9,9 @@ test("semantic roles honor all Color Scheme attributes and keep modifier styles"
[".cm-sem-function:not(.cm-sem-static)", "rgb(102, 136, 170)"],
[".cm-sem-parameter", "rgb(119, 153, 187)"],
[".cm-sem-constant", "rgb(136, 170, 204)"],
]) {
] as const) {
const role = page.locator(selector);
await expect(role).toHaveCSS("color", color!);
await expect(role).toHaveCSS("color", color);
await expect(role).toHaveCSS("background-color", "rgb(221, 238, 255)");
}
await expect(page.locator(".cm-sem-namespace")).toHaveCSS("font-style", "italic");
+23
Переглянути файл
@@ -80,6 +80,29 @@ test("⌘, opens Settings with the page tree; Escape closes", async ({ workbench
await expect(dialog).toBeHidden();
});
test("editor appearance groups related controls and keeps whitespace options editable", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("textbox", { name: "Search settings" }).fill("Show whitespaces");
await settings.getByRole("treeitem", { name: "Appearance", exact: true }).click();
const section = (name: string) => settings.getByRole("region", { name, exact: true });
await expect(section("Caret").getByRole("checkbox", { name: "Use block caret" })).toBeVisible();
await expect(section("Code Structure").getByRole("checkbox", { name: "Show line numbers" })).toBeVisible();
await expect(section("Code Assistance").getByRole("checkbox", { name: "Show intention bulb" })).toBeVisible();
const presentation = section("Presentation");
await expect(presentation.getByRole("checkbox", { name: "Render documentation comments" })).toBeVisible();
await expect(presentation.getByRole("textbox", { name: "Distraction free mode text width:" })).toBeVisible();
const whitespace = presentation.getByRole("checkbox", { name: "Show whitespaces" });
const leading = presentation.getByRole("checkbox", { name: "Leading", exact: true });
if (await whitespace.isChecked()) await whitespace.uncheck();
await expect(leading).toBeDisabled();
await whitespace.check();
await expect(leading).toBeEnabled();
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(settings).toBeHidden();
});
test("Language Servers page installs a tool with progress (in-memory installer)", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ for (const [id, selector] of [
["languages.servers", "[class*='body'] > [class*='language'][aria-label]"],
["plugins", "[class*='body'] > [class*='details']"],
["agents.list", "section[aria-label='Codex']"],
]) {
] as const) {
test(`${id} keeps its details usable beside the list`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
+93
Переглянути файл
@@ -0,0 +1,93 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Shelf keeps patch and file selection available in a narrow dock", async ({ workbench: page }) => {
const name = "Reconcile payment and settlement totals before exporting ledger reports";
const directory = "services/settlement/internal/payment-reconciliation/statement-generation";
const filename = "invoiceSettlementRowAssembler.ts";
const file = directory + "/" + filename;
await page.setViewportSize({ width: 1440, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ name, file }) => {
const root = "/dev/acme-api";
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: "1111111",
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_shelves = () => [
{
id: "settlement",
name,
timeMs: null,
branch: "main",
files: [file, "README.md"].map((path) => ({ path, kind: "modified", oldPath: null })),
},
{
id: "docs",
name: "Update release notes",
timeMs: null,
branch: "main",
files: [{ path: "CHANGELOG.md", kind: "modified", oldPath: null }],
},
];
h.vcs_shelf_diff = () => [];
const vcs = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ vcs);
useVcs.setState({ root, repo: root, roots: [root], available: true });
const project = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const settings = useProject.getState().settings ?? {};
useProject.setState({ settings: { ...settings, vcs: { ...settings.vcs, commit: { nonModal: true } } } });
const context = "/src/platform/context.ts";
(await import(/* @vite-ignore */ context)).setContext("vcsAvailable", true);
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 228);
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("vcs.showShelf");
},
{ name, file },
);
const panel = page.locator("[data-shelf-panel]");
const patches = panel.getByRole("tree", { name: "Shelved changes" });
const patch = patches.getByRole("treeitem").filter({ hasText: name });
await patch.click({ position: { x: 90, y: 12 } });
if ((await patch.getAttribute("aria-expanded")) === "false") await page.keyboard.press("ArrowRight");
const location = panel.getByText(directory, { exact: true });
await expect.poll(() => location.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
const divider = panel.getByRole("separator", { name: "Resize shelf panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const files = panel.getByRole("tree", { name: "Shelved files" });
await expect(files.getByRole("treeitem")).toHaveCount(2);
const pathBox = (await location.boundingBox())!;
const filesBox = (await files.boundingBox())!;
expect(pathBox.x).toBeLessThan(filesBox.x + filesBox.width - 50);
const row = files.getByRole("treeitem").filter({ hasText: filename });
await row.click({ position: { x: 90, y: 12 } });
await expect(row).toHaveAttribute("aria-selected", "true");
await panel.getByRole("button", { name: "Unshelve…", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Unshelve Changes" });
await expect(
dialog.getByRole("tree", { name: "Files to unshelve" }).getByText(filename, { exact: true }),
).toBeVisible();
await expect(dialog.getByText("README.md", { exact: true })).toHaveCount(0);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await page.evaluate(async () => {
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 640);
});
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(row).toHaveAttribute("aria-selected", "true");
await patches.getByRole("treeitem").filter({ hasText: "Update release notes" }).click();
await expect(files.getByRole("treeitem")).toHaveCount(1);
await expect(files.getByText("CHANGELOG.md", { exact: true })).toBeVisible();
});
+60
Переглянути файл
@@ -0,0 +1,60 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Stash wraps the current branch and accepts a multiline message in a narrow window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 380, height: 590 });
await stubDesktop(page);
const root = "/dev/settlement-engine";
const head = "release/QuarterlyInternationalSettlementReconciliationAndAuthorizationForMerchantOperations";
await page.evaluate(
async ({ root, head }) => {
const branch = { head, headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null };
const h = window.__ipc.handlers;
h.vcs_branch_info = () => branch;
h.vcs_roots = () => [{ root, ...branch }];
h.vcs_status = () => [];
h.vcs_stashes = () => [];
h.vcs_stash_push = () => null;
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.stash");
},
{ root, head },
);
const dialog = page.getByRole("dialog", { name: "Stash", exact: true });
await expect(dialog.getByText(`Current branch: ${head}`)).toBeVisible();
const body = dialog.locator("[data-dialog-body]");
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
const message = dialog.getByRole("textbox", { name: "Message", exact: true });
await expect(message).toBeFocused();
await message.fill("Set aside settlement work");
await message.press("End");
await message.press("Enter");
await expect(message).toHaveValue("Set aside settlement work\n");
await message.pressSequentially("Continue after the release.");
expect(await ipcCalls(page, "vcs_stash_push")).toEqual([]);
await dialog.getByRole("checkbox", { name: "Keep index" }).check();
await dialog.getByRole("checkbox", { name: "Include untracked files" }).check();
await message.press("Control+Enter");
await expect(dialog).toBeHidden();
await expect
.poll(() => ipcCalls(page, "vcs_stash_push"))
.toEqual([
{
repo: root,
message: "Set aside settlement work\nContinue after the release.",
keepIndex: true,
includeUntracked: true,
paths: null,
},
]);
});
+65
Переглянути файл
@@ -0,0 +1,65 @@
import { expect, openFromTree, test } from "./fixtures";
test("Switcher keeps the open file list and path visible in a narrow workbench", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const files = switcher.getByRole("listbox", { name: "Open files" });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
const selected = files.getByRole("option", { selected: true });
await expect(selected).toHaveText("README.md");
expect((await switcher.boundingBox())!.width).toBeLessThan(600);
await page.setViewportSize({ width: 400, height: 500 });
await expect.poll(async () => (await files.boundingBox())!.width).toBeGreaterThan(225);
const footer = switcher.locator("footer");
await expect(footer).toHaveText(/README\.md$/);
await expect(footer).toBeInViewport({ ratio: 1 });
await expect(footer).toHaveCSS("font-size", "12px");
expect(await tools.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
expect(await files.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const structure = tools.getByText("Structure", { exact: true });
expect(await structure.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await page.keyboard.press("Tab");
const activeTool = tools.getByRole("option", { selected: true });
await expect(activeTool).toBeInViewport({ ratio: 1 });
const firstTool = await activeTool.getAttribute("aria-posinset");
await page.keyboard.press("PageDown");
await page.keyboard.press("PageDown");
await expect(activeTool).not.toHaveAttribute("aria-posinset", firstTool!);
await expect(activeTool).toBeInViewport({ ratio: 0.98 });
expect(await tools.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await page.keyboard.press("Shift+Tab");
await expect(selected).toHaveText("README.md");
await page.keyboard.up("Control");
await expect(switcher).toBeHidden();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true");
});
test("Switcher takes up less space when both lists have only a few entries", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.evaluate(async () => {
const path = "/src/workbench/contributions.ts";
const { useContributions } = (await import(
/* @vite-ignore */ path
)) as typeof import("../src/workbench/contributions");
useContributions.setState(({ toolWindows }) => ({
toolWindows: new Map([...toolWindows].filter(([id]) => id === "project" || id === "terminal")),
}));
});
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
await expect(tools.getByRole("option")).toHaveCount(2);
await expect.poll(async () => (await switcher.boundingBox())!.height).toBeLessThan(380);
await expect(switcher.locator("footer")).toHaveText(/README\.md$/);
await page.keyboard.press("Escape");
await page.keyboard.up("Control");
});
+4 -8
Переглянути файл
@@ -1,12 +1,8 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
"lib": ["ES2024", "DOM", "DOM.Iterable"],
"types": ["node", "vite/client"]
},
"include": ["./**/*.ts", "../playwright.config.ts"]
"include": [".", "../playwright.config.ts", "../src/**/*.d.ts"]
}
+54
Переглянути файл
@@ -71,3 +71,57 @@ test("shows Update failures from the branch menu even when VCS notifications are
await expect(page.getByText(/untracked working tree files would be overwritten by merge/)).toBeVisible();
expect(await ipcCalls(page, "vcs_remote")).toHaveLength(1);
});
test("Update Project wraps long tracking branches and keeps its options reachable", async ({ workbench: page }) => {
await stubDesktop(page);
await page.setViewportSize({ width: 360, height: 580 });
const local = "release/" + "InternationalSettlementReconciliation".repeat(3);
await page.evaluate(async (head) => {
const root = "/dev/acme-api";
const branch = { head, upstream: `origin/${head}`, behind: 1, ahead: 1, operation: null, headCommit: "c1" };
const h = window.__ipc.handlers;
h.vcs_branch_info = () => branch;
h.vcs_roots = () => [{ root, head, headCommit: "c1", operation: null }];
h.settings_set = () => null;
h.vcs_remote = () => new Promise(() => {});
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.update");
}, local);
const dialog = page.getByRole("dialog", { name: "Update Project", exact: true });
await expect(dialog.getByText(`Update ${local} from origin/${local} (1 incoming)`)).toBeVisible();
const body = dialog.locator("[data-dialog-body]");
const width = await body.evaluate((el) => ({ scroll: el.scrollWidth, available: el.clientWidth }));
expect(width.scroll).toBe(width.available);
const reset = dialog.getByRole("button", { name: "Reset to the Remote Branch" });
await expect(reset).toBeVisible();
expect(
await reset.evaluate(
(el) => el.getBoundingClientRect().right <= el.closest('[role="dialog"]')!.getBoundingClientRect().right,
),
).toBe(true);
const merge = dialog.getByRole("radio", { name: /^Merge incoming changes/ });
const rebase = dialog.getByRole("radio", { name: /^Rebase the current branch/ });
await expect(merge).toBeChecked();
await merge.press("ArrowDown");
await expect(rebase).toBeChecked();
await dialog.getByRole("checkbox", { name: "Don't show again" }).check();
await dialog.getByRole("button", { name: "OK", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_remote"))
.toEqual([expect.objectContaining({ op: { op: "pull", rebase: true } })]);
expect(await ipcCalls(page, "settings_set")).toEqual(
expect.arrayContaining([
expect.objectContaining({ key: "vcs.git.updateMethod", value: '"rebase"' }),
expect.objectContaining({ key: "vcs.confirmation.showUpdateOptions", value: "false" }),
]),
);
});
+42
Переглянути файл
@@ -0,0 +1,42 @@
import { expect, test } from "./fixtures";
test("Welcome keeps project search and actions on one row at a narrow width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1080, height: 700 });
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
useProject.setState({ project: null, lightEdit: false });
});
const projects = page.getByRole("region", { name: "Projects", exact: true });
const search = projects.getByRole("textbox", { name: "Search projects" });
const list = projects.getByRole("listbox", { name: "Recent projects" });
const more = projects.getByRole("button", { name: "More Actions", exact: true });
const open = projects.getByRole("button", { name: "Open", exact: true });
await expect(list.getByRole("option")).toHaveCount(4);
await expect(more).toBeVisible();
await expect(open).toHaveText("Open");
await page.setViewportSize({ width: 440, height: 620 });
const boxes = await Promise.all([search.boundingBox(), open.boundingBox(), more.boundingBox()]);
expect(boxes[0]!.width).toBeGreaterThan(95);
for (const box of boxes.slice(1)) {
expect(Math.abs(box!.y + box!.height / 2 - (boxes[0]!.y + boxes[0]!.height / 2))).toBeLessThan(2);
expect(box!.x + box!.width).toBeLessThanOrEqual(440);
}
await expect(open.getByText("Open", { exact: true })).toBeHidden();
await expect.poll(() => projects.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await search.fill("tokio");
await expect(list.getByRole("option")).toHaveCount(1);
await expect(list.getByRole("option")).toContainText("tokio");
await more.press("Enter");
const menu = page.getByRole("menu", { name: "More Actions" });
for (const label of ["New File", "Open File", "Remote Development"]) {
await expect(menu.getByRole("menuitem", { name: new RegExp(label) })).toBeVisible();
}
await page.keyboard.press("Escape");
await expect(menu).toBeHidden();
await expect(more).toBeFocused();
await expect(search).toHaveValue("tokio");
});
Бінарний файл не відображається.
+26 -1
Переглянути файл
@@ -120,6 +120,17 @@ public final class OpenIdeaJdbc {
n++;
}
}
} else if (op.equals("schemaColumns")) {
// Every column of the namespace in one call (SQL completion), without primary keys.
header(out, "table", "name", "type", "nullable", "default");
try (ResultSet rs = m.getColumns(catalog, schema, "%", "%")) {
int n = 0;
while (rs.next() && n < 100000) {
row(out, rs.getString("TABLE_NAME"), rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
rs.getInt("NULLABLE") == 0 ? "0" : "1", rs.getString("COLUMN_DEF"));
n++;
}
}
} else {
header(out, "name", "type", "nullable", "default", "primary");
String table = a.get(1);
@@ -233,7 +244,7 @@ public final class OpenIdeaJdbc {
switch (op) {
case "open" -> open(a, reply);
case "schemas" -> schemas(reply);
case "tables", "columns" -> metadata(op, a, reply);
case "tables", "columns", "schemaColumns" -> metadata(op, a, reply);
case "namespace" -> {
header(reply, "namespace");
String name = null;
@@ -243,6 +254,20 @@ public final class OpenIdeaJdbc {
} catch (SQLException | AbstractMethodError ignored) {}
row(reply, name);
}
case "valid" -> {
// After a failed statement: whether the session survived (a dropped TCP
// connection leaves every later statement failing until the IDE reconnects).
header(reply, "valid");
boolean valid;
try {
valid = connection != null && !connection.isClosed() && connection.isValid(5);
} catch (AbstractMethodError | SQLFeatureNotSupportedException e) {
valid = true; // A pre-JDBC 4 driver cannot tell: keep the session.
} catch (SQLException e) {
valid = false;
}
row(reply, Boolean.toString(valid));
}
case "page" -> execute(work, a, reply, true);
case "query" -> {
if (a.size() == 3 || a.get(3).isEmpty()) {
+32
Переглянути файл
@@ -14,6 +14,7 @@ import java.util.logging.Logger;
public class SelfTest {
public static class Fixture implements Driver {
private boolean readonly;
private boolean dropped;
private int changes;
private Path started;
@@ -29,6 +30,12 @@ public class SelfTest {
case "getDatabaseProductName" -> "Fixture";
case "getDatabaseProductVersion" -> "1";
case "getIdentifierQuoteString" -> "\"";
case "getSearchStringEscape" -> "\\";
case "getSchemas" -> rows(List.of(Map.of("TABLE_SCHEM", "app")));
case "getColumns" -> "app".equals(a[1]) && "%".equals(a[2]) ? rows(List.of(
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "id", "TYPE_NAME", "INT", "NULLABLE", 0),
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1,
"COLUMN_DEF", "'none'"))) : rows(List.of());
default -> throw new SQLFeatureNotSupportedException();
});
return proxy(Connection.class, (p, m, a) -> switch (m.getName()) {
@@ -36,6 +43,21 @@ public class SelfTest {
case "getMetaData" -> meta;
case "close" -> null;
case "createStatement" -> statement();
case "isClosed" -> false;
case "isValid" -> !dropped;
case "getCatalog" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
/** A forward-only result set over `data`, read by column label. */
static ResultSet rows(List<Map<String, Object>> data) {
int[] at = {-1};
return proxy(ResultSet.class, (p, m, a) -> switch (m.getName()) {
case "next" -> ++at[0] < data.size();
case "getString" -> (String) data.get(at[0]).get((String) a[0]);
case "getInt" -> (Integer) data.get(at[0]).getOrDefault((String) a[0], 0);
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
@@ -53,6 +75,7 @@ public class SelfTest {
throw new SQLException("statement cancelled");
}
if (sql.equals("write") && readonly) throw new SQLException("read-only");
if (sql.equals("drop")) { dropped = true; throw new SQLException("connection reset"); }
changes++;
yield false;
}
@@ -122,6 +145,15 @@ public class SelfTest {
send(out, 5, "query", "after cancel", "0", "2");
var result = reply(in);
assert result[0] == 1 && result[result.length - 1] == 2;
send(out, 6, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("true");
send(out, 7, "query", "drop", "0", "2");
assert reply(in)[0] == 0;
send(out, 8, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("false");
send(out, 9, "schemaColumns", "app");
var columns = new String(reply(in), StandardCharsets.UTF_8);
assert columns.contains("orders") && columns.contains("note") && columns.contains("'none'") : columns;
} finally {
child.destroyForcibly().waitFor();
}
+1 -1
Переглянути файл
@@ -17,7 +17,7 @@
"format": "oxfmt",
"format:check": "oxfmt --check",
"knip": "knip",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit && tsrs -p e2e --noEmit",
"gen:bindings": "cargo test -p openidea --test export_bindings",
"gen:windows-icons": "node scripts/gen-windows-icons.ts",
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
+30
Переглянути файл
@@ -0,0 +1,30 @@
diff --git a/dist/index.cjs b/dist/index.cjs
index b20aa9d84be6ff4b85b126bdd930065277668a26..e677ab06ca9668407e202979e14b75ab7641d6b1 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -9675,7 +9675,9 @@ const hideNativeSelection = state.Prec.highest(EditorView.theme({
"& :focus": {
caretColor: "initial !important",
...drawMainRange ? {
- "&::selection, & ::selection": {
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
+ // whole subtree of every element that gains or loses focus.
+ "&::selection": {
backgroundColor: "Highlight !important"
}
} : {}
diff --git a/dist/index.js b/dist/index.js
index 216f754db06f65f7f17f056b47d8f6fab45067bf..22282993239d836ea1da19af10ccfc61b6480cc5 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -9670,7 +9670,9 @@ const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.th
"& :focus": {
caretColor: "initial !important",
...drawMainRange ? {
- "&::selection, & ::selection": {
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
+ // whole subtree of every element that gains or loses focus.
+ "&::selection": {
backgroundColor: "Highlight !important"
}
} : {}
+34 -25
Переглянути файл
@@ -323,6 +323,18 @@ const scroll: Scenario = {
},
};
/**
* Runs an action without a default shortcut from a key press: the press is the measured input,
* and the action runs in its handler, as from a key binding. Pause is bound to nothing.
*/
async function runActionOnKey(h: Harness, id: string) {
await h.page.evaluate((id) => {
const probe = (window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf;
addEventListener("keydown", () => void probe.runAction(id), { capture: true, once: true });
}, id);
await h.page.keyboard.press("Pause");
}
/**
* Git Log with 20,000 commits on branching lanes, loaded page by page as the
* backend does (150 ms a page, like `git log`): showing it, walking the
@@ -339,12 +351,7 @@ const gitLog: Scenario = {
).__openideaPerf.fakeGitLog(20_000, 150),
);
const showMs = await h.measure(
() =>
h.page.evaluate(() =>
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
"vcs.showLog",
),
),
() => runActionOnKey(h, "vcs.showLog"),
'[role="listbox"][aria-label="Commits"]',
"order flow step 0",
);
@@ -430,16 +437,13 @@ const resizePanels: Scenario = {
await h.page.evaluate(() =>
(window as never as { __openideaPerf: { fakeGitLog(n: number): void } }).__openideaPerf.fakeGitLog(2_000),
);
await h.measure(
() =>
h.page.evaluate(() =>
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
"vcs.showLog",
),
),
'[role="listbox"][aria-label="Commits"]',
"order flow step 0",
await h.page.evaluate(() =>
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
"vcs.showLog",
),
);
// Set-up, not measured: the splitters are dragged once the log is shown.
await h.inPage((p) => p.waitShown('[role="listbox"][aria-label="Commits"]', "order flow step 0", 10_000));
const refresh = await h.refreshMs();
const drag = async (name: string, dx: number, dy: number) => {
const box = (await h.page.getByRole("separator", { name }).boundingBox())!;
@@ -560,7 +564,9 @@ const agentTabs: Scenario = {
window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise<boolean> } }
).__openideaPerf.runAction("agents.openSampleConversations", { tasks: 2, turns: 150 }),
);
const shown = (n: number) => `[data-editor-focus] span[title="Sample task ${n}"]`;
// The conversation shown: its requests end with its task's title.
const SHOWN = "[data-editor-focus] [data-message]";
const title = (n: number) => `(Sample task ${n})`;
// Both conversations get their earlier entries painted in background batches, also the
// first one, hidden behind the second as soon as it opened.
await h.page.waitForFunction(
@@ -575,25 +581,28 @@ const agentTabs: Scenario = {
// Rows painted while hidden are laid out the first time their conversation shows.
for (const n of [1, 2]) {
await h.page.getByRole("tab", { name: `Sample task ${n}` }).click();
await h.page.locator(shown(n)).waitFor();
await h.page
.locator(SHOWN, { hasText: title(n) })
.first()
.waitFor();
await h.page.waitForTimeout(300);
}
// WebKit restyles a hidden conversation in full when it is shown again (Chromium keeps its
// style): what bounds that there is the history's DOM, and rows skipping rendering off screen.
const { conversationNodes, rowsAlwaysRendered } = await h.page.evaluate((selector) => {
const conversation = document.querySelector(selector)!.closest("[data-editor-focus]")!;
const conversation = document.querySelector(selector)!;
const rows = [...conversation.querySelector("[data-message]")!.parentElement!.children];
return {
conversationNodes: conversation.querySelectorAll("*").length,
rowsAlwaysRendered: rows.filter((r) => getComputedStyle(r).contentVisibility !== "auto").length,
};
}, shown(2));
}, "[data-editor-focus]");
const t0 = await h.now();
const before = await h.counters();
const switches: number[] = [];
for (let i = 0; i < 10; i++) {
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), shown(i % 2 ? 2 : 1)));
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), SHOWN, title(i % 2 ? 2 : 1)));
await h.page.waitForTimeout(150);
}
const work = Harness.delta(before, await h.counters());
@@ -602,10 +611,7 @@ const agentTabs: Scenario = {
// Scrolling up from the end, a step at a time: how far the text under the pointer moves
// beyond the scroll itself.
const scrollJumps = await h.page.evaluate(async (selector) => {
const stream = document
.querySelector(selector)!
.closest("[data-editor-focus]")!
.querySelector("[data-message]")!.parentElement!;
const stream = document.querySelector(selector)!.parentElement!;
const frame = () => new Promise(requestAnimationFrame);
stream.scrollTop = stream.scrollHeight;
await frame();
@@ -626,7 +632,7 @@ const agentTabs: Scenario = {
}
stream.scrollTop = stream.scrollHeight;
return jumps;
}, shown(2));
}, SHOWN);
const refresh = await h.refreshMs();
const box = (await h.page.locator("[data-editor-focus]").boundingBox())!;
@@ -732,6 +738,9 @@ const projectTree: Scenario = {
async run(h) {
const generated = h.page.locator('[role="treeitem"][aria-level="2"]', { hasText: "generated" }).first();
await generated.click();
// Measure from a settled selection: a key pressed in the click's own frame also pays for that frame.
await generated.and(h.page.locator('[aria-selected="true"]')).waitFor();
await h.page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
const expandMs = await h.measure(
() => h.page.keyboard.press("ArrowRight"),
'[role="tree"][aria-label="Project"]',
Створено
+20 -24
Переглянути файл
@@ -7,6 +7,9 @@ settings:
overrides:
mermaid>katex: ^0.18.2
patchedDependencies:
'@codemirror/view': 0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5
importers:
.:
@@ -61,7 +64,7 @@ importers:
version: 6.7.6
'@codemirror/view':
specifier: ^6.43.14
version: 6.43.14
version: 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@floating-ui/react-dom':
specifier: ^2.1.9
version: 2.1.9([email protected]([email protected]))([email protected])
@@ -85,7 +88,7 @@ importers:
version: 1.2.0
'@replit/codemirror-vim':
specifier: 6.4.0
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))
'@tanstack/react-virtual':
specifier: ^3.14.21
version: 3.14.21([email protected]([email protected]))([email protected])
@@ -591,7 +594,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-JSlhgoK+/g1TGJI5NuADx2+6syhxnQNLCWLXyO5QLFyetomcr/vIxSdiNlmyAv963YXUzCuwAwRG6npZ5xyJ1A==}
@@ -1069,7 +1071,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==}
@@ -1083,14 +1084,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==}
@@ -1864,7 +1863,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
@@ -1878,14 +1876,12 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
@@ -2391,14 +2387,14 @@ snapshots:
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@codemirror/[email protected]':
@@ -2438,7 +2434,7 @@ snapshots:
'@codemirror/lang-javascript': 6.2.5
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/css': 1.3.9
'@lezer/html': 1.3.13
@@ -2454,7 +2450,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/lint': 6.9.7
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/javascript': 1.5.6
@@ -2464,7 +2460,7 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11
@@ -2488,7 +2484,7 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11
@@ -2499,7 +2495,7 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/markdown': 1.8.0
@@ -2562,7 +2558,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/xml': 1.0.6
@@ -2606,7 +2602,7 @@ snapshots:
dependencies:
'@codemirror/state': 6.7.6
'@codemirror/streamparser': 6.0.0
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11
@@ -2619,21 +2615,21 @@ snapshots:
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
crelt: 1.0.7
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/highlight': 1.2.5
style-mod: 4.1.4
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
crelt: 1.0.7
'@codemirror/[email protected]':
@@ -2642,7 +2638,7 @@ snapshots:
'@codemirror/[email protected]': {}
'@codemirror/[email protected]':
'@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)':
dependencies:
'@codemirror/state': 6.7.6
crelt: 1.0.7
@@ -3105,13 +3101,13 @@ snapshots:
'@replit/[email protected]': {}
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))':
dependencies:
'@codemirror/commands': 6.11.1
'@codemirror/language': 6.13.1
'@codemirror/search': 6.7.2
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@replit/codemirror-vim-core': 0.1.0
'@rolldown/[email protected]':
+2
Переглянути файл
@@ -3,3 +3,5 @@ allowBuilds:
overrides:
# GHSA-238p-pmpm-9mq7 (fixed in 0.18.2); mermaid 12.1 still asks for katex ^0.16.
mermaid>katex: ^0.18.2
patchedDependencies:
"@codemirror/view": patches/@codemirror__view.patch
+177 -7
Переглянути файл
@@ -106,7 +106,12 @@ impl Forward {
type Channels = Arc<Mutex<HashMap<u64, (Channel<ChannelFrame>, u64)>>>;
#[derive(Default)]
pub struct Connections(Mutex<HashMap<String, Arc<Connection>>>);
pub struct Connections {
windows: Mutex<HashMap<String, Arc<Connection>>>,
/// The connect attempt allowed to publish for each window. A later connect, or a
/// disconnect, supersedes an attempt that is still starting the server.
attempts: Mutex<HashMap<String, u64>>,
}
impl Connection {
/// Commands of a remote window that run on this machine follow this machine's decision about the
@@ -143,13 +148,13 @@ impl Connection {
impl Connections {
pub fn get(&self, window: &str) -> Option<Arc<Connection>> {
self.0.lock().get(window).cloned()
self.windows.lock().get(window).cloned()
}
/// The window connected to folder `root` of `target`.
pub fn window_of(&self, target: &RemoteTarget, root: &str) -> Option<String> {
let root = root.trim_end_matches('/');
self.0
self.windows
.lock()
.iter()
// A dev container is one project: its folder there is only known once connected.
@@ -162,17 +167,131 @@ impl Connections {
/// Every connected window.
pub fn all(&self) -> Vec<(String, Arc<Connection>)> {
self.0.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect()
self.windows.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect()
}
/// Starts a connect for `window`. An older attempt can no longer publish.
pub fn begin(&self, window: &str) -> u64 {
self.bump(window)
}
fn bump(&self, window: &str) -> u64 {
let mut attempts = self.attempts.lock();
let next = attempts.get(window).copied().unwrap_or(0).wrapping_add(1);
attempts.insert(window.to_owned(), next);
next
}
/// Installs `connection` when `attempt` is still the one [`begin`] returned for `window`.
/// An older attempt leaves the connection a newer one published.
pub fn publish(&self, window: &str, attempt: u64, connection: Arc<Connection>) -> bool {
let attempts = self.attempts.lock();
if attempts.get(window).copied() != Some(attempt) {
return false;
}
if let Some(old) = self.windows.lock().insert(window.to_owned(), connection) {
old.peer.kill();
old.forwards.lock().clear();
}
true
}
pub fn disconnect(&self, window: &str) {
if let Some(c) = self.0.lock().remove(window) {
// Invalidate an attempt that has not published yet, or it would put the
// connection back after this disconnect.
self.bump(window);
if let Some(c) = self.windows.lock().remove(window) {
c.peer.kill();
c.forwards.lock().clear();
}
}
}
/// `ssh://` / `wsl://` / `devcontainer://` location, the same spelling the frontend stores.
pub fn remote_location(target: &RemoteTarget, path: &str) -> String {
let (scheme, name) = match target {
RemoteTarget::Ssh { config } => ("ssh", config.as_str()),
RemoteTarget::Wsl { distro } => ("wsl", distro.as_str()),
RemoteTarget::DevContainer { folder, .. } => ("devcontainer", folder.as_str()),
};
let config = match target {
RemoteTarget::DevContainer { config, .. } if !config.is_empty() => format!(":{}", encode_uri_component(config)),
_ => String::new(),
};
let path = if path.starts_with('/') { path.to_owned() } else { format!("/{path}") };
format!("{scheme}://{}{config}{path}", encode_uri_component(name))
}
/// The remote project a `ssh://`, `wsl://` or `devcontainer://` location names.
pub fn parse_remote_location(location: &str) -> Option<(RemoteTarget, String)> {
let (kind, rest) = if let Some(rest) = location.strip_prefix("ssh://") {
("ssh", rest)
} else if let Some(rest) = location.strip_prefix("wsl://") {
("wsl", rest)
} else {
("devcontainer", location.strip_prefix("devcontainer://")?)
};
let slash = rest.find('/')?;
if slash == 0 {
return None;
}
let authority = &rest[..slash];
let path = rest[slash..].to_owned();
let (name, config) = if kind == "devcontainer" {
match authority.split_once(':') {
Some((name, config)) => (name, config),
None => (authority, ""),
}
} else {
(authority, "")
};
let name = decode_uri_component(name)?;
let config = decode_uri_component(config)?;
if name.is_empty() {
return None;
}
let target = match kind {
"ssh" => RemoteTarget::Ssh { config: name },
"wsl" => RemoteTarget::Wsl { distro: name },
_ => RemoteTarget::DevContainer { folder: name, config },
};
Some((target, path))
}
/// `encodeURIComponent`: the frontend builds locations with it.
fn encode_uri_component(value: &str) -> String {
let mut out = String::new();
for b in value.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn decode_uri_component(value: &str) -> Option<String> {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return None;
}
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok()?;
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
/// Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload).
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -512,6 +631,9 @@ pub async fn remote_connect(
});
progress(RemoteStage::Connecting, None);
let label = AppState::owner_window(window.label()).to_owned();
// A later connect or a disconnect supersedes this attempt, so it cannot replace
// the connection that one published — or put one back after it was dropped.
let attempt = state.remote_dev.begin(&label);
let channels: Channels = Arc::default();
let connection_slot: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>> = Arc::default();
let handler = Arc::new(ClientHandler {
@@ -613,10 +735,14 @@ pub async fn remote_connect(
if let RemoteTarget::DevContainer { folder, config } = &target {
forward_configured_ports(&connection, folder, config).await;
}
state.remote_dev.disconnect(&label);
if !state.remote_dev.publish(&label, attempt, connection.clone()) {
tracing::debug!("{label}: remote connection superseded");
connection.peer.kill();
connection.forwards.lock().clear();
return Err(IdeError::cancelled());
}
state.host.close_project(&label);
state.host.mcp_reports.set_remote(&label, std::path::PathBuf::from(&connection.root));
state.remote_dev.0.lock().insert(label.clone(), connection.clone());
let weak = Arc::downgrade(&connection);
let peer = connection.peer.clone();
let auth_plugins = state.plugins.clone();
@@ -641,6 +767,9 @@ pub async fn remote_connect(
sync_plugin_languages(&plugins, &connection, &label).await;
sync_plugin_packages(&plugins, &connection, &label).await;
});
if let Err(error) = crate::window_groups::persist(window.app_handle()).await {
tracing::warn!(%error, "cannot save window session after opening remote project");
}
Ok(RemoteProject { target, root, host, server_version: info.version, os: info.os, commands, project })
}
@@ -1069,6 +1198,29 @@ async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Dur
mod tests {
use super::*;
#[test]
fn remote_locations_round_trip_like_the_frontend() {
let cases = [
(RemoteTarget::Wsl { distro: "Ubuntu-24.04".into() }, "/home/me/app", "wsl://Ubuntu-24.04/home/me/app"),
(RemoteTarget::Ssh { config: "my box".into() }, "/srv/app", "ssh://my%20box/srv/app"),
(
RemoteTarget::DevContainer { folder: "/work/app".into(), config: "devcontainer.json".into() },
"/workspaces/app",
"devcontainer://%2Fwork%2Fapp:devcontainer.json/workspaces/app",
),
(
RemoteTarget::DevContainer { folder: "/work/app".into(), config: String::new() },
"/workspaces/app",
"devcontainer://%2Fwork%2Fapp/workspaces/app",
),
];
for (target, path, location) in cases {
assert_eq!(remote_location(&target, path), location);
assert_eq!(parse_remote_location(location), Some((target, path.to_owned())));
}
assert!(parse_remote_location(r"\\wsl.localhost\Ubuntu\home\me\app").is_none());
}
#[test]
fn a_command_missing_on_a_server_of_another_version_says_which_versions() {
let missing = || IdeError::unavailable("-32601: command web_url is not available remotely");
@@ -1159,6 +1311,24 @@ mod tests {
}
}
#[tokio::test]
async fn a_later_connect_supersedes_an_earlier_attempt() {
let connections = Connections::default();
let first = connections.begin("main");
let second = connections.begin("main");
let older = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/old"));
assert!(!connections.publish("main", first, older.clone()));
assert!(connections.get("main").is_none());
let newer = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/new"));
assert!(connections.publish("main", second, newer.clone()));
assert!(Arc::ptr_eq(&connections.get("main").unwrap(), &newer));
connections.disconnect("main");
assert!(connections.get("main").is_none());
assert!(!connections.publish("main", second, newer.clone()));
older.peer.kill();
newer.peer.kill();
}
#[tokio::test]
async fn the_server_does_not_decide_trust_for_commands_run_here() {
let tmp = tempfile::tempdir().unwrap();
+7 -4
Переглянути файл
@@ -143,10 +143,11 @@ impl AppState {
/// Opens `root` in `window` and records it in the recent projects.
pub fn open_project(&self, window: &str, root: &Path) -> IdeResult<Arc<Project>> {
// A local project replaces a remote one in this window.
self.remote_dev.disconnect(window);
let project = self.host.open_project(window, root)?;
self.record_project(&project)?;
// Drop the remote connection only once the local project is actually open.
// A failed open leaves the window on the host it is still routing to.
self.remote_dev.disconnect(window);
Ok(project)
}
@@ -166,14 +167,16 @@ impl AppState {
/// Opens `window` for editing the loose file `file` (LightEdit); not a recent project.
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
let project = self.host.open_light(window, file)?;
self.remote_dev.disconnect(window);
self.host.open_light(window, file)
Ok(project)
}
/// LightEdit without a file (File › New File from a welcome window).
pub fn open_light_empty(&self, window: &str) -> IdeResult<Arc<Project>> {
let project = self.host.open_light_empty(window)?;
self.remote_dev.disconnect(window);
self.host.open_light_empty(window)
Ok(project)
}
/// Called on the event-loop thread (window destruction, the `close_project`
Loaded 100 of 331 files, more files were not shown because too many files have changed in this diff. Show more