Commit Graph
212 Commits
Author SHA1 Message Date
Micha Reiser 32669b2743 [ty] Add project-manager.project configuration (#30568)
## Summary

Adds a new `project-manager.project = "uv" | "none"` configuration
setting, similar to the existing script setting, so that users can
opt-in without relying on `TY_UV`.


This PR does not implement the `auto`, that would derive the project
manager from the project layout. It's something we can add later. It
also doesn't add support for `project-mode = "sync" | "metadata"`.
Again, this is something we can do later. For now, `project-mode` is
always `metadata`.

Closes https://github.com/astral-sh/ty/issues/5067.

Testing: CLI, project, server, and file-watching tests passed.
2026-11-24 08:49:14 +00:00
Micha Reiser 981d44c9cb [ty] Rename uv-metadata diagnostic to project-manager and improve its wording (#30528)
## Summary

This does some polishing on the former `uv-metadata` diagnostic:


### Rename 
It renames the diagnostic from `uv-metadata` to `project-manager`. This
is to make it less uv focused (we could support other project managers)
and also make it less technical. `uv-metadata` is an implementation
detail. For as far as users are concerned, ty failed to run the project
manager to set up the Python environment or to load the project
metadata.

**Before**

```
warning[uv-metadata]: uv 0.12.2 is too old; upgrade `./old-uv` to uv 0.12.3 or newer
--> pyproject.toml:1:1

Found 1 diagnostic
```

**After**

```
warning[project-manager]: Failed to load project metadata from uv: Found uv 0.12.2, but uv 0.12.3 or newer is required
--> pyproject.toml:1:1
help: Upgrade `./old-uv` to uv 0.12.3 or newer

Found 1 diagnostic
```

### Setting subdiagnostic

We now also attach a sub diagnostic that explains why ty uses the
project manager when ty failed to find a supported uv version. This will
become more important once we make the uv integration for scripts opt
out.

**Before**

```
error[uv-metadata]: Failed to invoke `uv workspace metadata`: failed to resolve uv executable: cannot find binary path
--> script.py:2:1

Found 1 diagnostic
```

**After**

```
error[project-manager]: Setting up the Python environment with uv failed: could not find `uv` on `PATH`
--> script.py:2:1
info: ty uses uv to install this script's dependencies because `project-manager.script` is set to `"uv"`
 --> script.py:5:28
  |
5 | # project-manager.script = "uv"
  |                            ^^^^ configured here
info: To install uv, see https://docs.astral.sh/uv/

Found 1 diagnostic
```


### uv error message

I changed how we show uv's error message when it fails to resolve
dependencies:



**Before**

```
error[uv-metadata]: `uv workspace metadata` failed with `exit status: 1`
--> script.py:2:1
info: No solution found when resolving dependencies
  cause: Because missing-script-dependency was not found in the cache and you require missing-script-dependency==99.0.0, we can conclude that your requirements are unsatisfiable.

hint: Packages were unavailable because the network was disabled. When the network is disabled, registry packages may only be read from the cache.

Found 1 diagnostic
```

**After**

```
error[project-manager]: Setting up the Python environment with uv failed
--> script.py:2:1
error: No solution found when resolving dependencies
  cause: Because missing-script-dependency was not found in the cache and you require missing-script-dependency==99.0.0, we can conclude that your requirements are unsatisfiable.

hint: Packages were unavailable because the network was disabled. When the network is disabled, registry packages may only be read from the cache.
error: `uv workspace metadata` exited with status 1

Found 1 diagnostic
```

I don't love it, but formatting this one is a bit tricky, because uv
doesn't provide us with structured output and we need to preserve any
whitespace as is, to not mess up uv provided code frames.

And concise

```
script.py:2:1: error[project-manager] Setting up the Python environment with uv failed: No solution found when resolving dependencies
Found 1 diagnostic
```



## Notes to reviewers

Stacked on #30527.

Verified the diagnostics in full and concise CLI output and in the
language server.
2026-11-19 12:46:15 +00:00
Micha ReiserandZsolt Dollenstein b1d5da7fa2 [ty] Isolate uv-managed scripts from the project environment (#30461)
## Summary

This PR fixes an issue found by @zsol. Today, with uv sync enabled, a
script uses the project's virtual environment for the short period
before the script's sync completes (unless the script has its own
`tool.ty` section). This is because the script inherits the project's
configuration.

With this PR, scripts that opt in to uv sync now start with no virtual
environment. ty replaces the virtual environment with uv's environment
when the sync completes (or keeps an empty environment when the sync
failed, preserving the script's isolation).


Related to #30460.

The project, script preparation, and file rename tests passed.

---------

Co-authored-by: Zsolt Dollenstein <zsol.zsol@gmail.com>
2026-11-18 13:35:50 +01:00
Micha Reiser b6d8e21241 [ty] Add project-manager.script = "uv" (#30489)
## Summary

This PR adds a new `project-manager` table:

```toml
[project-manager]
project = "uv" | "auto" | "none"
project-mode = "sync" | "metadata"
script = "uv" | "none"
```

This PR only implements the script part, but I listed all options to
outline where we want to go with this in the future.

`script = "uv"` opts in to installing PEP 723 script dependencies with
uv (to reduce the need for `TY_UV`). For now, `project-manager.script`
defaults to `"none"`, but I plan to change this to `"uv"` in the near
future. The new option follows the same configuration precedence as
other script settings:

* A script with its own `tool.ty` section uses the value from its own
table to control whether it uses uv to sync its dependencies or not.
* Scripts without a `tool.ty` section use the project level
`project-manager.script`

For now, overriding the setting based on file patterns isn't supported
(I have no strong reason against it, it's mainly to cut scope).

`TY_UV` takes precedence over any setting in the configuration (similar
to other CLI options that support environment variables).

The recommended way to check untrusted code is to set `TY_UV=off`, which
overrides `project-manager.script`.

For now, we keep supporting `experimental.useUv` for scripts, but the
in-editor `configuration.project-manager.script` takes precedence over
`experimental.useUv`.

## Why is the setting not under `environment.

For projects, setting `project-manager.project = "metadata"` also
changes how we discover the project (we prefer the workspace over the
closest ty project), and `metadata` doesn't initialize the Python
environment.

## LSP watch mode

Changing `project-manager.script` at the project level requires saving
any open script (or closing and reopening) for the sync to start. This
simplified the implementation a fair bit and seems an okay trade off.
2026-11-18 12:42:42 +01:00
Micha Reiser b48f42a7e7 [ty] Sync script environments when opening the file, when using diagnosticMode: "openFilesOnly" (#30381)
## Summary

With uv script support enabled, opening a workspace currently reads
every project file to find PEP 723 scripts, even if only two ordinary
Python files are open. In `openFilesOnly` and `off` diagnostic modes, ty
now defers synchronizing scripts until they're opened or saved. This
avoids syncing all scripts when opening a workspace. We continue to sync
all scripts when using `diagnosticMode: "workspace"`, because we need
the initialized environment to check each script.

In `openFilesOnly` and `off`, a file rename can skip imports in a closed
script that need its uv environment to resolve. Find References started
from a package installed only for that script can also miss calls in the
script. This is similar to how ty (and all other LSPs in fact), can't
find references in closed notebooks.

The same limitation applies when expanding a call or type hierarchy into
a closed script. For example, Call Hierarchy can show the script’s
function but omit calls from it into a dependency. Opening a package
directly from the script’s site-packages can also leave imports within
that package unresolved. Opening the script lets ty resolve those
imports after uv finishes. If the script’s dependencies change on disk
while it is closed, ty picks up the change on reopen.

Workspace Symbols still lists definitions in closed scripts. Its search
has always been limited to project files.

I believe this is the right trade off. `diagnosticMode: "openFilesOnly`
is closer to `ty check <open_files>`. You don't want to pay for overhead
(or memory) of files you're not working on.

## Test plan

With `openFilesOnly`, uv script support, and dynamic file watching
enabled in both windows, the baseline (left) syncs `report.py` when the
workspace opens. The change (right) syncs it when the file opens.


https://github.com/user-attachments/assets/fdcb5b22-553c-44df-8e88-9f90c56a96bd

## Performance

Mean wall time from server startup on the two-open-file Home Assistant
workload from #29697, over 10 paired runs with `TY_UV=scripts` on both
builds.

| Home Assistant workload | Base (`cd68b32092`) | Deferred sync |
| --- | ---: | ---: |
| First diagnostic report | 200.4 ms | 82.9 ms |
| Both diagnostic reports | 227.3 ms | 106.7 ms |

Both builds returned identical diagnostics. The base indexed 9,589 files
on every run, while this change left the project index lazy.

## Test Plan

In the same test workspace, ty resolved `attrs` only after opening the
script in open-files-only mode and resolved it for workspace diagnostics
without ever opening the script.
2026-11-17 15:25:21 +00:00
Micha Reiser 7794e10f40 [ty] Report workspace diagnostics while scripts initialize (#30410)
## Summary

Today, we defer workspace diagnostics while uv sync is running. This was
mainly because of a concern for how we resolved `file_settings` before
https://github.com/astral-sh/ruff/pull/30407 (see that PR for details).

This PR changes workspace diagnostics to return empty diagnostics for a
file that has a pending uv synchronization. This is matches the pull
diagnostic behavior for scripts. ty triggers a new workspace diagnostic
pull when the uv synchronization finishes (successfully or not).

The reason we show no diagnostic while the synchronization is running is
that there's little value in showing import errors before the
environment is ready. Deferring the diagnostics prevents that (and
avoids an annoying flickering if the environment initializes very
quickly).


## Test plan

Both recordings open the same Ruff workspace with two intentional type
errors and a short delay on the last uv sync. Both files are closed when
their diagnostics arrive.

**On main**, the Problems panel stays empty until the last script
finishes syncing. Then both errors appear.


https://github.com/user-attachments/assets/f5001349-a69f-49f8-9dbe-d3ff96e9e447

**With this PR**, the error in `_find_ruff.py` appears during sync. The
error in `update_schemastore.py` appears when its environment is ready.


https://github.com/user-attachments/assets/a6af09ac-7e22-45f3-8ca6-331807995987
2026-11-17 15:15:54 +00:00
Lérè 4228f4c216 [ty] Update imports when renaming Python package folders (#30084)
## Summary

Editors that support `workspace/willRenameFiles` can now request import
updates when a Python package folder is renamed within its parent
directory. One request can include both file and folder renames.

Closes https://github.com/astral-sh/ty/issues/4945.

## Approach

Register a folder filter alongside the Python file filter. The rename
handler returns edits against the original paths, including edits to
files inside the renamed directory.

## Test Plan

See included tests.
2026-11-16 21:47:19 -08:00
Micha Reiser 8a90960b92 [ty] Fix stale diagnostic when using diagnosticMode: "workspace" (#30415)
## Summary

Today, ty looks only at the final batch to decide whether to keep a
workspace diagnostic pull open. If ty streams every changed diagnostic
as a partial result, the final batch is empty, so ty suspends the pull.
The switch to `gen-lsp-types` introduced this regression when the
handler lost the distinction between a complete report and the last
batch of a streamed report.
[#24894](https://github.com/astral-sh/ruff/pull/24894)

If the user then fixes an error that ty streamed for `a.py`, ty retries
the suspended pull with its original `previousResultIds`. Those IDs
predate the error, so ty can miss that it needs to clear the diagnostic
for `a.py`, leaving the fixed error in the Problems panel.

With this change, ty tracks changes across the entire pull. After
streaming the error for `a.py`, ty sends a final response even if the
final batch is empty. The client can then include the result ID for
`a.py` in its next pull, allowing ty to clear the diagnostic when the
file is fixed. Pulls with no changes still long-poll.

The new regression test reproduced the timeout with uv disabled, and all
32 pull-diagnostics tests passed with the fix.
2026-11-16 16:08:08 +01:00
Brent Westbrook 244668339a Adopt new APIs from Rust 1.98 (#30419)
Summary
--

- The first commit uses [strip_circumfix] to remove paired delimiters in
one call.
- The second commit uses [map_or_default] to combine many `map` and
`unwrap_or_default` calls.
- The third commit uses [bool::ok_or] to turn boolean checks into
`Result<(), E>` values.
- The fourth commit uses [str::substr_range] to get the byte range of a
TODO directive directly from the comment.

The last commit is slightly more involved than the others, as Codex
found a panic in the old code if
a `HACK` TODO comment used the Kelvin sign as its `K` and added a test
showing that `substr_range`
helped to fix it. That seems absurdly niche, but the new code is simpler
anyway.

There's also a new [format_into] API for formatting integers into a
`NumBuffer` and bypassing some
`Display` overhead. We could use this in the `UP031` fix, but it makes
the code a bit more
complicated and seemed worth trying and benchmarking separately to see
if it's worth the trouble.

[strip_circumfix]:
https://doc.rust-lang.org/stable/std/primitive.str.html#method.strip_circumfix
[map_or_default]:
https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map_or_default
[bool::ok_or]:
https://doc.rust-lang.org/stable/std/primitive.bool.html#method.ok_or
[str::substr_range]:
https://doc.rust-lang.org/stable/std/primitive.str.html#method.substr_range
[format_into]:
https://doc.rust-lang.org/stable/core/primitive.usize.html#method.format_into
2026-11-16 10:04:15 -05:00
Alex WaygoodandMicha Reiser 22e77392fb [ty] Split invalid-return-type into 3 focussed rules; rename empty-body and unsound-return (#29947)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-11-11 16:59:57 +00:00
Micha Reiser c6304b1af5 [ty] Fall back to a workspace-wide watch when file watcher registration fails (#30120)
## Summary

When Eglot hits its file watch limit, ty retries the same registration
on every edit, which can stall typing. If the client rejects the
per-path watches, ty now requests a single workspace-wide `**` watch for
the rest of the session. If that request also fails, ty keeps any
previously accepted watch and stops retrying.

Addresses the repeated registrations in
https://github.com/astral-sh/ty/issues/4950.

## Test Plan

The LSP end-to-end suite passed, including coverage for clients that
accept or reject the fallback.
2026-11-10 13:36:55 +01:00
Lérè 8f0018c29f [ty] Add support for workspace/willRenameFiles LSP request (#28330)
## Summary

This adds `workspace/willRenameFiles` support so editors can update
Python imports and references before actually renaming or moving
underlying files. The changes that we issue are best-effort rather than
necessarily complete, and they cover indexed files and open documents
(including unsaved changes) across workspaces.

The scope of rename behaviour in this delivery is described in
https://github.com/astral-sh/ruff/pull/28329.

Closes https://github.com/astral-sh/ty/issues/1560.

## Approach

We introduce a background request handler that calls
`ty_ide::will_rename_files` in each project with the supported subset of
rename requests and that project's indexed files and open documents. The
handler then converts the resulting source edits to LSP positions and
combines them into one workspace edit against the original document
locations.

## Test Plan

See included tests.
2026-11-05 14:29:37 -08:00
Alex Waygood c86652abce [ty] Skip active Conda and Pixi environments during discovery if the environment doesn't contain Python (#30066) 2026-11-05 15:58:48 +00:00
Micha Reiser 27452ba5b0 [ty] Don't fail configuration deserialization on conflicting rule names (#30023)
## Summary

A configuration that sets different levels for the rule and its alias
(e.g. `unresolved-import` and `import-not-found`) currently fails to
deserialize. This PR removes the validation from the configuration
deserialization path because failing during deserialization:

* Means the LSP has to fallback to the default configuration, loosing
all other user configuration. This is certainly not what users wan.t
* ty stops config discovery if it finds an invalid `pyproject.toml`,
even if there's a higher precedence `ty.toml` (ty fails on a
configuration that it isn't even using)
* serde errors don't have the same nice code frames. E.g. the old
implementation underlined the entire rules table.


Instead, we should validate the settings when converting from options to
settings. This ensures:

* That we can recover in the LSP case
* It gives us nice code frames that point to the name in the rules
table.

However, I decided to remove the error altogether in favor of my stacked
PR that adds a warning when using a deprecated rule name. The reasoning
here is:

* I don't think we should show two warnings at the same location. 
* This aligns with how we handle misspelled rule names, which is also a
warning only (and is/was a long requested change on the ruff repository)
* It matches ruff's behavior
* I don't see much harm in running ty, especially because it also gives
much better recovery in the LSP.
* ty resolves overrides lazily when resolving the settings for a
specific files. At that point, it's too late to error if the main config
and the override use both the new and alias rule name
* There are cases where options appear as if they're from a single file
when they're not. E.g., VS Code merges user-level and workspace-level
configurations. For example,
  user-settings:
  ```json
  {
    "ty.configuration": {
      "rules": { "unresolved-import": "ignore" }
    }
  }
  ```
  workspace-settings:
  ```json
  {
    "ty.configuration": {
      "rules": { "import-not-found": "warn" },
      "environment": { "extra-paths": ["./stubs"] }
    }
  }
  ```
  are merged to:
  ```json
  {
    "rules": {
      "unresolved-import": "ignore",
      "import-not-found": "warn"
    },
    "environment": {
      "extra-paths": ["./stubs"]
    }
  }
  ```
It's now hard to make an argument what the user intention was, and
failing in this case seems overly strict to me.


The path taken in this PR is to, instead, give higher precedence to the
new rule name.
## Test Plan

Added CLI and editor regression coverage and ran the CLI, project, and
editor configuration tests.
2026-11-04 16:36:21 +00:00
Alex Waygood 0471c14d1f [ty] Rename unresolved-import to import-not-found (#29960)
## Summary

ty currently reports `unresolved-import` for both a missing module and a
missing member in a `from` import. But the word "unresolved" is heavily
overloaded in Python, and has been reported by users as being confusing
(see https://github.com/astral-sh/ty/issues/2471). This PR renames the
rule to `import-not-found`, which describes the lookup failure in either
case.

Configuration, command-line flags, and ignore comments accept either
spelling. If several flags set this rule’s severity using different
spellings, the last flag wins. Existing baseline entries still match,
and rewriting a baseline uses the new name. Links to the old rule
heading still work.
2026-11-03 19:53:26 +00:00
Charlie Marsh 371dd377b7 [ty] Fix a call hierarchy panic when expanding outgoing calls (#29964)
## Summary

In Trio, open the outgoing call hierarchy for `notify_closing`, insert a
line at the top of the file, and expand the original item. Its saved
position now points at the imported `enable_ki_protection` decorator. We
walk the decorator’s body and interpret its call-site offsets in the
much shorter caller file, which panics during UTF-16 position
conversion.

This can also happen without an edit. A property setter and its
inherited getter can resolve together, even though the getter lives in
another module.

We now compute outgoing calls from definitions in the prepared item’s
file.
2026-11-03 14:40:36 -05:00
Micha Reiser 207ec3affe [ty] Add diagnostic baseline support (#27636) 2026-10-26 13:34:01 -07:00
Charlie Marsh bfa2407e98 [ty] Skip script discovery when uv script environments are disabled (#29697)
## Summary

With two files open in Home Assistant, skipping script discovery reduced
the language server’s mean time to first diagnostics from 465 ms to 354
ms on Linux (24%). Previously, ty indexed 10,768 files looking for PEP
723 scripts, even though uv integration was off by default and ty had no
script environments to prepare.

We now scan for scripts to prepare uv environments at startup and on
reload only when uv script environments are enabled (`TY_UV=scripts` or
`TY_UV=1`). With uv off, ty still reads an open script’s inline
settings.

The benchmark client doesn’t register file watchers. With dynamic file
watching enabled, ty still scans for script-specific import paths; five
paired runs showed no startup gain in that configuration.
2026-10-25 07:11:44 -04:00
David Peter ceb9eea7aa [ty] Add return-type inlay hints (#29437)
## Summary

Show return-type inlay hints for unannotated functions in the playground
and in editors that support it:

<img width="478" height="278" alt="image"
src="https://github.com/user-attachments/assets/52145f44-ab5d-4fc1-8621-d54207d49454"
/>

Return types can also be "baked in". After double clicking:

<img width="478" height="278" alt="image"
src="https://github.com/user-attachments/assets/3d6ee13c-6cd7-4a1a-b1f2-e347030ddffe"
/>

And here it is in VS Code (baking in works as well):

<img width="580" height="148" alt="image"
src="https://github.com/user-attachments/assets/c59725fe-22e4-4eac-b534-6bb9561efdec"
/>


## Test plan

New snapshot tests. Also tested interactively in the playground and in
VS Code.
2026-10-19 12:04:54 +02:00
David Peter 068e06a3c9 [ty] Add return-type-inference configuration (#29323)
## Summary

Introduce a new configuration option `analysis.return-type-inference`
which can be used to control the return type inference feature, which
we'll introduce in #29253. I will not merge this PR without the one on
top, but it seemed like a good idea to split it out for easy review.
2026-10-15 21:13:58 +02:00
Charlie Marsh 4d6a7db787 [ty] Fix notebook cell lookups after cells with cell magics (#29308)
## Summary

We now resolve notebook requests to the correct Python cell after cells
containing a cell magic such as `%%bash`. Previously, hovering `x` in an
`x = 1` cell could show the type of `z` from the following `z = "zz"`
cell.

The server identifies cells by their position in the notebook, but
`Notebook::cell_range` used that index to look up offsets among Python
cells only. We now translate between those indices and return no range
for cells excluded from the Python source. Semantic token and folding
range requests for those cells return no results instead of falling back
to the whole notebook.
2026-10-13 09:15:14 -04:00
Charlie Marsh eb9e9bdcf9 [ty] Clamp notebook cell positions to the end of the cell (#29307)
## Summary

We now clamp notebook request positions to the end of the requested
cell's content. For example, `(0, 1)` in an empty cell resolves to `(0,
0)`, consistent with the [LSP rule for character offsets beyond the end
of a
line](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/lsp/3.17/types/position.md).

Previously, we converted positions against the concatenated notebook
source, allowing a position past the end of a cell to resolve into a
later cell. Hovering just past an empty cell could show the type of `x`
from a following `x = 1` cell, and an inlay hint request could return
hints from the next cell.

We now bound position conversion by the cell's content range, excluding
its synthetic separator newline. If the cell has no source range, we
return `None` instead of falling back to the start of the notebook.
2026-10-13 09:15:13 -04:00
Charlie Marsh 2e696c7c86 [ty] Fix panic on completions past the end of a notebook's last cell (#29306)
## Summary

This PR fixes a completion panic in a notebook with an empty last cell.

To analyze a notebook, we combine its Python cells into one source
string, adding a newline after each cell:

```text
First cell:       "x = 1"       at offsets 0..5
Empty last cell:  ""            at offsets 6..6
Combined source:  "x = 1\n\n"  at offsets 0..7
```

We parse the cells separately, but the resulting module describes the
combined source. Previously, we ended that module at offset 6, where the
empty cell's content ends. Position conversion uses the combined source,
so a request for character 1 of the empty cell can resolve to offset 7.
That is the end of the source, but it was outside the module's range.
Looking up the completion position then panicked with `Range is not
contained within root`.

We now give the module the range 0..7, as we would when parsing the same
source as a whole. This makes positions at the end of the combined
source safe to look up. #29307 separately corrects position conversion
so the same request resolves to offset 6, the end of the requested
cell's content.

Closes https://github.com/astral-sh/ty/issues/4687.
2026-10-13 09:15:13 -04:00
Charlie Marsh c00103fb4e [ty] Fix deadlock when requests arrive before workspace configuration (#29303)
## Summary

We now process ready worker actions before replaying requests deferred
while waiting for `workspace/configuration`. Previously, a large
deferred request burst could fill both bounded queues: workers waited to
enqueue responses while the main loop waited to enqueue more jobs,
leaving the server unresponsive.

This extends the existing priority for worker actions to deferred
requests while preserving client message order. The regression test
queues 64 hover requests before replying to configuration, then checks
that all requests and a subsequent hover receive responses.

Closes https://github.com/astral-sh/ty/issues/4707.
2026-10-12 15:31:54 -04:00
Brent Westbrook ef23c9c39e Update default and latest Python versions for 3.15 (#28792)
Summary
--

This PR updates our default Python version to 3.11, in line with 3.10
reaching [EOL] next month, and
updates our latest Python version to 3.15. I followed last year's PR
(#20725) to find everywhere
that needed to change. Fortunately there were not as many test changes
needed as last year's
deferred annotation issues.

I also updated the language classifier in our pyproject.toml.

[EOL]: https://devguide.python.org/versions/#supported-versions

Test Plan
--

Existing tests with updated snapshots. Most of the updates were to
snapshots for TC001, TC002, and
TC003, which now default to the lazy-import fix.

After updating the snapshots, I tried to make sure we still had coverage
for whatever changed. That
meant adding a few more mdtests for the TC rules, and one small mdtest
for RUF017 to restore
coverage for the `functools.reduce` fix.
2026-10-09 12:26:57 -04:00
Micha Reiser b6a74d26cb [ty] Refresh uv project metadata when uv files change (#28529)
## Summary

Refresh the `uv workspace metadata` when a user manually changes the
project structure, a `pyproject.toml`, `uv.toml`, or after changing the
active environment using e.g. `uv add`, `uv sync`, or `uv pip`.


ty now watches refetches the uv metadata when:

* a `uv.toml`, `pyproject.toml`, `uv.lock` or `.python-version` file
changes
* a `.dist-info` directory is created or deleted, same for
`site-packages`
* A new included directory is created or deleted (could be a new
workspace member)

I intentionally limited this PR to workspace layouts where all members
are within the workspace root. Members outside aren't watched, to keep
the implementation simpler (we also couldn't watch those paths when `uv`
initially fails because ty then doesn't even know the member's path).

It was also my goal to balance the watcher complexity with avoiding
unnecessary `uv workspace metadata` calls. In most cases, I preferred a
simpler watcher implementation over avoiding unnecessary calls because a
`uv workspace metadata` call for an unchanged workspace should be very
cheap.

## Review

I recommend reviewing this PR commit by commit.
2026-10-01 18:30:32 +02:00
Micha Reiser aa9a1ff88a [ty] Avoid stale I/O diagnostics when closing deleted files (#28988) 2026-10-01 15:19:13 +02:00
Micha Reiser 0d7e203568 [ty] Improve uv metadata diagnostics (#28990)
## Summary

This PR improves the uv-metadata diagnostics. Specifically, it fixes
that uv-metadata diagnostics spawn multiple lines when using
`output-format=concise`.

* Concise: `warning[uv-metadata] Failed to load uv metadata: No solution
found when resolving dependencies`: `Failed to load uv metadata:
{first_line_in_uv_output}`.
* Full: `uv workspace metadata` failed with `{status}` + subdiagnostic
with the details
  ```
error[uv-metadata]: `uv workspace metadata` failed with `exit status: 1`
          --> script.py:2:1
          info: No solution found when resolving dependencies
cause: Because missing-script-dependency was not found in the cache and
you require missing-script-dependency==99.0.0, we can conclude that your
requirements are unsatisfiable.
  
hint: Packages were unavailable because the network was disabled. When
the network is disabled, registry packages may only be read from the
cache.
  
  ```


Now, this is all best-effort:

* Concise: Only taking the first line could theoretically result in a
mid-sentence truncation if uv emits a multiline summary message.
* Full: Rendering `info: {first_line}` risks that second line is
misaligned if it line e.g. annotates the first line.

I don't think there's much we can do about this without uv emitting
structured diagnostics.

The first two commits restructure the uv file watching tests and change
them to show the diagnostic output. While not strictly necessary for
this change, a separate PR felt a bit overkill.

I recommend reviewing this commit by commit.



## Test Plan

Focused CLI, LSP, and uv file-watching tests pass.
2026-09-29 15:59:40 +02:00
Micha Reiser dab6370667 [ty] Fix anchoring of include and exclude patterns after the project's root changed (#28995) 2026-09-29 12:41:41 +00:00
Micha Reiser 226201fef0 [ty] Refresh Python settings when virtual environments change (#28650)
## Summary

This PR is a first step towards updating the project's uv metadata when
the virtual environment changes. The scope of this PR is to add the
non-uv specific virtual environment file watching. That is, it adds the
necessary file watching handling to update the detected virtual
environment and its Python version when:

* a `pyenv.cfg` changes
* the default `.venv` or the explicitly specified `environment.python`
virtual environment gets created or deleted.


Unfortunately, this does require storing the path to the resolved
virtual environment in `ProgramSettings`. Otherwise, we'd have to
resolve it every time we see a related file watcher event. It's
unfortunate because it doesn't feel like a setting. But there isn't
really any better to carry forward this information.


I recommend reviewing this PR commit by commit.


## Test Plan

Native file-watching regression tests pass.
2026-09-27 18:48:09 +02:00
Lérè 9327d5d362 [ty] Fulfill language-server requests against closed documents (#28595)
## Summary

This allows language-server clients to request document symbols, hover
information, and other document features without first sending
`textDocument/didOpen`. Requests can target local files within workspace
folders or configured import search paths, as well as cached copies of
ty's bundled typeshed stubs. This includes files excluded from type
checking (e.g., through
[`src.exclude`](https://docs.astral.sh/ty/exclusions/)).

Fixes https://github.com/astral-sh/ty/issues/3624.

## Approach

Existing request handlers can now read closed documents through the
selected project's database without registering those documents as open.

Additionally:

- Open documents continue to use the client's text, including unsaved
edits.
- Requests against closed documents preserve the existing diagnostic
policies and do not add files to the set selected for type checking. For
example, `openFilesOnly` mode returns no diagnostics for closed
documents.
- Unopened notebooks remain unsupported because the client supplies
their cell URIs and position mappings.

## Test Plan

See included tests.
2026-09-23 00:31:10 -07:00
Lérè 96fa587512 [ty] Select projects for external files using import search paths (#28594)
## Summary

In preparation for [supporting language server requests against closed
documents](https://github.com/astral-sh/ruff/pull/28595), this changes
analysis project selection for an external file[^1] such that we
preferentially select a project whose import search paths contain the
file in question. This makes it so that language server requests against
an external file use Python environment and editor settings that are
relevant to it.

[^1]: A file outside of any workspace folder.

## Approach

Previously, the project selection logic for an external file would
select the first project from the list of all projects sorted by
workspace-folder. That selection was, effectively, arbitrary, and was
used even when another project's import search paths contained the file.
[Session::project_root_for_path](https://github.com/astral-sh/ruff/blob/1ffb87ef81bb2becffd20bd04b554cbf2fafc52b/crates/ty_server/src/session.rs#L531-L544)
now falls back to searching for a project with matching import search
paths once we've confirmed that the file is outside every workspace
folder.

Additionally:

- When several projects match the new heuristic, we break ties by
selecting the first project from the list of all projects sorted by
workspace-folder path. Likewise if no project matches the heuristic, we
select the first project from that sorted list (as we did by default
before).
- Both requests and document updates use the same project selection
algorithm. This keeps the analysis environment and editor settings
consistent when a file opens or closes, and ensures edits reach the
database used for analysis.
- No prior import or analysis is required for us to use this new project
selection heuristic.

## Test Plan

See included tests.
2026-09-23 00:31:09 -07:00
Lérè 46aaafafa8 [ty] Use workspace editor settings for external files (#28639)
## Summary

We currently use default editor settings in the language server when
responding to requests against an external file (one that falls outside
every workspace folder). This happens even though that file is analyzed
using an existing project. This behaviour can cause us to ignore
settings such as `completions.autoImport = false`, which are supplied
during language server initialization or through workspace
configuration.

This change ties editor settings for external files to the selected
project: when no workspace folder contains the opened file, we use the
settings of the workspace folder associated with the project that we
select for analysis. Under the existing project selection rules, this is
the project whose workspace folder path sorts first lexicographically.

Fixes https://github.com/astral-sh/ty/issues/2993.

## Approach

Workspace selection now handles both filesystem paths and virtual paths
in one place:
[`Session::workspace_root_for_document`](https://github.com/astral-sh/ruff/blob/be89e399bfa11060668834ebbe5b5f4595e6944a/crates/ty_server/src/session.rs#L517-L521).
The helper returns a workspace-folder path using the existing
project-selection rules, including the fallback when no workspace
matches.

Returning a path lets both immutable and mutable project lookup use the
same selection logic, while
[`Session::snapshot_document`](https://github.com/astral-sh/ruff/blob/be89e399bfa11060668834ebbe5b5f4595e6944a/crates/ty_server/src/session.rs#L1185-L1199)
uses that path to retrieve editor settings. This removes the separate
project and settings fallbacks for virtual files and the duplicated
workspace search in mutable project lookup.

## Test Plan

Please see included tests.
2026-09-23 00:31:09 -07:00
Charlie Marsh 4d322b8eca [ty] Filter diagnostics before computing result IDs (#28759)
## Summary

Changing `showSyntaxErrors` could leave cached syntax errors visible
even after a client requested fresh diagnostics. We computed result IDs
from the raw diagnostics, then filtered syntax errors during LSP
conversion, so a request carrying the previous result ID incorrectly
returned an unchanged report.

We now filter diagnostics before computing result IDs and use the same
filtered diagnostics for LSP output. Disabling syntax errors clears
cached errors without requiring an edit, while files with no syntax
errors retain their cached results. Workspace requests continue long
polling when filtering leaves no diagnostics to report.
2026-09-22 06:50:07 -04:00
Charlie Marsh e86121d0d1 [ty] Refresh diagnostics after workspace configuration changes (#28755)
## Summary

Adding or replacing a workspace can change diagnostics for existing
files, but clients could keep displaying stale results until those files
were edited. We now send `workspace/diagnostic/refresh` after applying
workspace configuration changes when the client supports it, since
re-registering diagnostic support alone does not invalidate cached
results.

We skip the initial configuration, when there are no cached diagnostics
to refresh. Initialization is tracked for the session, so replacing the
only workspace still triggers a refresh even though removing it
temporarily leaves no projects.

Closes https://github.com/astral-sh/ty/issues/4463.
2026-09-21 13:18:26 -04:00
Micha Reiser fd5d636bdd [ty] Watch script dependencies in the language server (#28522)
## Summary

Same as https://github.com/astral-sh/ruff/pull/28125 but for the server.

The main difference to the CLI is that, up to now, the server did not
support changing its watched paths after its initial initialization.
This PR adds the infrastructure so that the server now supports updating
its watched paths as search paths change.


## Test Plan

**Before**



https://github.com/user-attachments/assets/a6ace5a1-84c9-4acb-a15c-991389543109

Changes to `dependency.py` are not picked up

**Now**


https://github.com/user-attachments/assets/b3d6bf4b-496f-4bdc-a610-82eb9690ffb3
2026-09-17 19:56:58 +02:00
Micha Reiser 689dc812f3 Rename TokenKind::Name to Identifier (#28667) 2026-09-17 15:47:10 +02:00
Micha Reiser 72b1fd3cef [ty] Preserve valid LSP settings when configuration resolution fails (#28653) 2026-09-17 09:48:31 +02:00
Alex WaygoodandMicha Reiser 12132db288 [ty] Isolate uv integration tests from inherited environment settings (#28342)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-09-08 13:09:55 +02:00
Micha Reiser 12e65d6d7e [ty] Prevent LSP hangs during inlay hint bursts (#28390) 2026-09-08 10:16:40 +02:00
Alex Waygood 71b790029c [ty] Move ty_ide's importer to ty_python_semantic (#28170)
Future autofixes will need to introduce imports alongside code changes.
In particular, there are cases where inserting `assert_never(...)` would
be useful, but the fix often also needs to import `assert_never`. The
importer currently lives in `ty_ide`, so diagnostics emitted by
`ty_python_semantic` cannot use it.

Move the importer into `ty_python_semantic` and reuse it from
completions and inlay hints. As its first use in a diagnostic, attach
the `reveal_type` import fix directly to `undefined-reveal`, replacing
the custom LSP handling. The fix imports from `typing` on Python 3.11+
and `typing_extensions` on older Python versions.

Cache source-style detection and top-level import discovery in Salsa per
file, so diagnostics in separate inference regions and IDE features can
share the setup. The cached data does not retain the parsed AST or a
copy of the source text.

Stacked on #28169.
2026-09-06 00:29:01 +01:00
Zsolt Dollenstein f4839591d6 [ty] Add a missing-direct-dependency rule (#28001)
This PR replaces #25027. It adds an opt-in check for imports of
installed distributions that the current project does not declare
directly in `pyproject.toml`.

## Overview

The check uses ty's existing uv workspace integration (`TY_UV=1`) to
call `uv workspace metadata --frozen --active`. uv now provides module
ownership without synchronizing the environment, so ty can read the
metadata without installing packages or updating `uv.lock`.

The metadata provides:

1. Each workspace project's runtime and optional dependencies.
2. Dependencies declared in dependency groups.
3. Importable modules and their owning distributions, including source
paths for editable installs.

During import inference, ty maps each resolved import to its
distribution and compares it against the importing project's direct
declarations. If the declaration is missing, ty emits
`missing-direct-dependency`, naming the distribution to add. Each
distribution is reported once per file, at its first unsuppressed
import.

The rule is disabled by default and requires an existing, synchronized
environment. Unavailable or incompatible dependency metadata disables
the check; rejected dependency metadata produces a debug message.

## Nuances

- Editable installs may lack entries in uv's module-owner map. ty uses
their source paths to attribute resolved imports.
- Files identified as package code require runtime or optional
dependencies. Non-package files, such as tests and scripts, can also use
dependency groups, but those groups' transitive dependencies still need
direct declarations.
- For `from package import child`, a resolved child module is checked
against its own distribution rather than the parent's. Imports with
unknown or ambiguous ownership are skipped.
- Ownership metadata is used only when the explicitly selected Python
environment matches uv's environment.
- The current integration covers directory checks. Explicit file
arguments, `--config-file`, and standalone PEP 723 scripts do not use
the workspace's dependency declarations.

The schema and rule documentation are regenerated. Most of the
rule-documentation diff consists of updated source-line links.
2026-08-28 14:01:44 +00:00
Micha Reiser 47c81c8b4a [ty] Move script environment initialization to the CLI and LSP (#28038)
## Summary

This PR moves from a lazy PEP 723 script discovery do eagerly discover
all scripts as part of the project's file discovery.


There are two motivations for doing this:

1. Initializing the script's environment before checking the script is
not sufficient. Other files can import the script, and type inference
can then resolve `file_settings` and `python_version_with_source` which
are both environment dependent (the former less so, but uv can tell us
the python version). Initializing all scripts before we start checking
ensures that type inference sees the right environment even when a
script has been imported. This is the bug that Zsolt identified in my
initial PEP 723 PR.
2. Today, the LSP only initialized scripts when the user opened them.
However, that means that their environment isn't available as part of
find references and workspace symbols. This can result in missed
references (note, making find references return all project and script
references when searching for references of a shared dependency requires
a few changes to find references as well, but this sets the foundation
for it). Initializing all environments when opening the project ensures
the environments are available when running find references (or the user
can rerun find references once all syncs are complete, but they don't
have to open every script just to make sure that find references will
show the references in them)
3. Knowing all scripts simplifies file watching because we now have
distinct points where script environments can change, and may require
updating the watched paths.


Now, there are a few downsides as well, but I think this is the right
trade off (honestly, I don't know how to fix 1 easily without it, and 3
was the main reason why I considered this approach even before Zsolt
found the bug).

* Unlike before, the LSP now indexes and reads all project files. This
can mean that startup now takes a second or so on very large projects
where it was instant before, because we didn't do any form of indexing.
This also means that the LSP retains more memory for projects that don't
use workspace diagnostics (or find references), because the LSP now
loads all files into memory to determine whether a file is a script.
This is inherent to the approach. I suspect that we can mitigate the
"all source in memory" in the future by only storing compressed source
text, which should reduce memory usage by about 70%.
* We now sync all scripts on LSP startup. I could see this become a
problem in workspaces with many (with 100 or 1000s scripts). If this
becomes a problem, I think we can a) limit script sync to on-open,
accepting that find-references etc. may require opening the relevant
scripts and/or b) allow users to selectively sync scripts by using a LSP
command. For now, I think syncing all scripts should be fine, given that
uv is fast (the first time might take a while)
* I had to make the uv sync queue unbounded. It's still bounded by the
number of scripts and projects. But we no longer apply back pressure if
the sync requests start piling up. The reason I had to remove it is
because we don't want a `didChange` or `didOpen` to block, only because
there are already 8 queued scripts. But more importantly, we don't want
to block the LSP startup until all scripts have synchronized, but
queuing them up during startup would just have done that (because the
main loop blocks everytime time the queue is full). I think this is
okay, and I'll add another PR on top of this one that adds cancellation
support for sync requests. I also think that our previous back pressure
wasn't as impactful as I thought
* We now sync scripts before checking the files. That means, ty no
longer makes progress on checking other project files while the syncs
are pending. This is the one I'm the most bumped about. It was so cool
that ty often checked the entire project while waiting on uv to finish
syncing. To mitigate, I increased the worker pool to N/4 where N is max
parallelism and, while testing, I also found that syncinc all scripts,
at least in Ruff's repo, is instant once uv is warm.

I think this also gets us into a position where adding support for
nested projects becomes much easier, because they'll naturally fit in.
We'll discover nested projects as part of indexing `Files` (we'd need to
move that off `Project`), synchronizing their environments can happen at
the exactly same points as synchronizing scripts. The biggest remaining
lift is to change `ty_project` and `ProjectDatabase` to no longer assume
that there's a single `Project` (but there is still one main project).


## Test Plan

CLI


https://github.com/user-attachments/assets/db370cde-d9db-4c85-8772-06b608ce6587



https://github.com/user-attachments/assets/ae6e825a-6814-4dc0-8b2f-630469de1a8d
2026-08-28 13:09:04 +02:00
Micha Reiser 0e60c897b8 [ty] Refresh uv project metadata in the background (#27933)
## Summary

This refactors the project's `uv workspace metadata` call to run in the
background, the same as for scripts. This ensures that the watch command
and the LSP remain responsive and show a progress indicator while uv is
running.

It should also make it easier to run `uv workspace metadata --sync` for
projects. Although, that does require some work so that we can surface
progress from the initial uv call (during project discovery) and not
have the LSP blocked until the command completes.

This PR does not change when we run `uv workspace metadata`. That is, it
doesn't add logic to detect when uv needs to rerun. The same as before,
`uv workspace metadata` is only called when the `pyproject.toml`
changed. It isn't run when a `uv.toml` or the virtual environment
changes. We should do so, but this should be its own PR.

This PR enables `TY_UV=1 ty check --watch`

## Review

I recommending reviewing this PR commit by commit and with whitespace
changes disabled.


## Test Plan

LSP:



https://github.com/user-attachments/assets/8c1ab9df-8209-44d5-b0b2-ba06cb824625



1. Simulate a long `uv metadata` command (e.g. when `uv sync` is holding
the lock for multiple seconds). You can see the progress report
2. Changes to a `pyproject.toml` trigger a refresh

CLI


https://github.com/user-attachments/assets/b3cde596-c7f5-4f2e-880b-d3885c02dcb8
2026-08-28 13:09:04 +02:00
Micha Reiser 5b1b3fb240 [ty] Synchronize saved script metadata on open (#27873)
## Summary

ty supports in-memory changes, but uv always reads the script's content
from disk. This discrepancy could lead to ty skipping a sync when,
between opening a file and saving it, the script metadata block wasn't
changed, but it changed compared to what was saved on disk when the file
was opened.

The root cause of this issue is that ty computes the script-fingerprint
from the current file content (which may include in-memory changes).
Instead, it should compute the fingerprint as it is seen on disk.

I considered a few different approaches:

* Support reading the persistent content in `ruff_db`: Add a new
`persisted_source_text` query, track the persisted `File` revision and
the in-memory revision separately. `ScriptsEnvironments` can then
compute the fingerprint based on the persisted source text.
* Use `system.read_text` in `ScriptsEnvironments`. I disregarded that
quickly because we proactively trigger the synchronization of all
scripts in a few places and we rely on this bailing quickly if the files
are unchanged (we don't want to read each script to bail).
* Introduce a new `Force` sync mode and use it in `didSave`. 

I'd pick the first approach if we had multiple frontends that supported
in-memory changes. But, given that it's only the LSP, I started with the
`Force` sync mode, and I almost opened a PR for it. During the final
cleanups, I realized that there's a much simpler LSP-only fix (the CLI
doesn't have this problem).


We don't need a `persisted_source_text` query if we schedule the script
synchronization before we set the Script's in-memory content in
`didOpen`. That is, first trigger the synchronization, then open the
file and load its in-memory content. That's all we need.

Fixes astral-sh/ty#4250. 

## Test Plan

**Before**

Reload VS Code with unsaved changes, hit save. Note how the script block
isn't synced (because we didn't make any changes to it)



https://github.com/user-attachments/assets/cd050b94-08a3-4c61-ba14-4a3f1b7a1e48

**This PR**

Same sequence, but the sync runs.



https://github.com/user-attachments/assets/c8acc477-7666-4411-a9b4-df33328ccb7e
2026-08-28 13:09:03 +02:00
Micha Reiser c7fe174832 [ty] Fix Goto definition in script dependencies (#27747)
## Summary

Each script with inline metadata (PEP 723) gets its own virtual
environment with its own dependencies. This is to guarantee isolation.


Before for this PR, go to definition only worked when resolving an
import directly in a script. E.g. `from mypyp_primer.projects import
get_projects`, clicking on projects resolved successfully. However, all
go to definition requests within `mypy_primer.projects` failed (unless
the main project had `mypy_primer` installed as a dependency).


The root cause of this was in `db.program_file(db, file)`. The method's
responsibility is to resolve the most likely program to use for `file`.
Today, `db.program_file(db, file)` only handled two cases:

* It's a first-party and it has inline metadata (PEP 723). Use the
script's `Program`. This is why clicking on `mypy_primer.projects`
worked from within the script
* Otherwise, use the `Project`'s program


Because of that, any script dependency used the `Project`'s `Program`
instead of the script's.


This PR extends `db.program_file(db, file)` with a heuristic for
third-party files (it's important that `db.program_file(db, file)` is
accurate for first-party files, for third-party files, the best we can
do is "guess"). That is, iterate over all known `Program`'s and use the
`Program` for which file appears on the search paths. Use `Project` as
the fallback (still the best guess if everything else fails).


This operation isn't expensive but it also isn't cheap. However, we only
call `db.program_file` at API boundaries. That is, we mainly call it
once for each LSP request. There are a few where the method is called
more than once (2 or three times, constant factor), but these are all
first-party files, for which `db.program_file` keeps using the
fast-path. That's why I don't think it's justified to Salsa cache this
resolution. But we can if this turns out to be a performance bottleneck
in the future.

Closes https://github.com/astral-sh/ty/issues/4253

## Test Plan


https://github.com/user-attachments/assets/5cff9f33-cb54-46d9-9f33-82f1ee63999b


Added language-server integration coverage and ran the affected test
suites and Clippy.
2026-08-28 12:45:52 +02:00
Micha Reiser 754d633bd7 [ty] Highlight PEP 723 script metadata as TOML (#27746)
## Summary

This PR adds support for TOML syntax highlighting in PEP 723 inline
metadata blocks by emitting TOML specific tokens during semantic
highlighting. I know, this wasn't really something we planned on adding
but I got annoyed by starring at large gray blocks and it was too easy.

This approach is relatively straightforward, and has the advantage that
it works for all editors. However, it also comes with limitations:

* Parentheses matching and completions don't work
* It can't easily support inserting `# ` on enter (when adding a new
line)
* No support for go to def, hover etc (we could add them, but it becomes
a bit more questionable whether this is in ty's scope)

To support these features, we'd have to add an embedded grammar to
ty-vscode (and other editors). I think this is still something worth
considering, and the approach taken here doesn't prevent us from doing
this. That's why I decided to go with this easier and cross-editor
implementation for now.

The emitted tokens are inspired by the grammars of VS Code toml
extensions.

Note: I'm only aware of sublime supporting semantic highlighting of
inline metadata. I don't think pyrefly or pylance do.

## Test Plan

<img width="1245" height="603" alt="Screenshot 2026-08-14 at 11 07 41"
src="https://github.com/user-attachments/assets/120785d5-18a9-478e-af65-77819446b2d2"
/>
2026-08-28 12:45:51 +02:00
Micha Reiser 49af405180 [ty] Synchronize PEP 723 script environments in the language server (#27619)
This completes https://github.com/astral-sh/ty/issues/4183 across all
surfaces by integrating the uv script environment synchronization into
the language server.

As explained in earlier PRs. The main challenge in the LSP are:

* Low latency: We don't want a uv synchronization to block unrelated
requests (for other files) or requests that don't need the initialized
virtual environment (go to def and semantic tokens already work decently
without an initialized virtual environment)
* Avoid flickering diagnostics: We want to avoid diagnostics
disappearing and reappearing. Specifically, diagnostics should not
disappear when you declare a new dependency only to then reappear when
the synchronization is complete. Instead, keep using the old virtual
environment while syncing the new environment so that completions,
diagnostics, semantic tokens etc remain unchanged until the sync is
complete. This gives a much nicer and more consistent experience than
throwing away the outdated virtual environment or simply returning empty
diagnostics while syncing.
* The LSP supports in-memory changes, uv does not. This PR avoids this
issue in most cases but not all. I opened a follow up issue to fix the
one instance that I'm aware of where this could lead to ty skipping a
synchronization when it should instead trigger a resync. I have ideas of
how to fix this, it just requires touching a few core infrastructure
pieces, which would unnecessarily bloat this PR (and I think the case is
uncommon enough that we can ship an initial version with this known
bug).


The script support hooks in to the following notifications:

* `didOpen`: Trigger a sync when the user opens a file in the
background. Use an empty virtual environment while the sync is running.
Skip diagnostics to avoid showing false-positives (we don't want to show
a bunch of unresolved import errors).
* `didSave`: Trigger a resync to update the virtual environment if the
inline metadata changed
* `didChangeWatchedFiles`: Trigger a resync for files that changed on
disk (that aren't open) but that ty analyzed before (e.g. when using
workspace diagnostics).

The notable omission is `didChange`. I decided not to sync on change.
Mainly because uv doesn't provide a way to pass the file content via
stdin. But also because syncing on every change might be a bit
excessive. This is something we can reconsider once uv supports syncing
in-memory changes.


Closes https://github.com/astral-sh/ty/issues/4183 (this entire stack)


## Opt In

This PR adds a new `experimantal.useUv` server setting. It has three
modes:

* `off`: default, today's behavior, ty doesn't use uv to sync script
environments
* `scripts`: Use uv to sync scripts, but not to retrieve project
metadata
* `on`: Use all supported uv integrations (the same as `scripts` for
now)


I expect that we'll iterate on the setting options, but it roughly is
the same as `TY_UV`, just for the LSP. It's also likely that this
setting will make it into ty's persistent configuration. But I decided
to defer that, because a persistent setting has a higher cost and I
don't know where to add this setting (new `uv` section or is it
`environment.use_uv` or something else)?

## Test plan


https://github.com/user-attachments/assets/2782ac93-1ea4-44ff-bc8b-a22ff33c89a7


https://github.com/user-attachments/assets/8dabd518-0985-4fa5-adb2-24ced78c0469
2026-08-28 12:45:51 +02:00
Micha Reiser 248de0b701 [ty] Skip scripts with an invalid PEP 723 configuration (#27505)
## Summary

Skip checking scripts with invalid PEP 723 metadata blocks, that are,
blocks that ty can't parse successfully or configurations that don't
resolve successfully. Instead, emit one diagnostic that points to the
invalid metadata.

ty still initializes a `Program` for each of those scripts so that LSP
operations continue to work. But we skip those scripts in all code paths
where we perform semantic checks.

Fixes https://github.com/astral-sh/ty/issues/4181.

## Test plan

Added tests
2026-08-20 10:34:53 +02:00
Micha Reiser bd9c92c67c [ty] Support pull diagnostics for notebook cells (#27778) 2026-08-19 08:16:17 +02:00