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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 6f1c3a7b0f fix(settings): import Java annotation colours as IntelliJ shows them
Importing an IntelliJ color scheme mapped only DEFAULT_METADATA to the
annotation colour. Java annotations use ANNOTATION_NAME_ATTRIBUTES, which the
bundled Default and Darcula schemes set themselves, so a scheme that only
changes DEFAULT_METADATA shows the parent's annotation colour in IntelliJ but
the file's default after import. The importer now reads
ANNOTATION_NAME_ATTRIBUTES ahead of DEFAULT_METADATA, applies the parent's
value when a Default- or Darcula-based file leaves it out, and exports the
colour under that key.

Fixes #6108
2026-11-26 17:08:27 +08:00
langxpтаkradme 925d474274 fix(app): resume interrupted update downloads (#5377)
An interrupted update download started again from zero on the next attempt. The update is now downloaded to a .part checkpoint in the app cache, keyed by version, target and signature so the GitHub and CNB sources share it, and later attempts resume it with an HTTP Range request. A 200 answer or a mismatched range replaces the checkpoint safely (the old bytes stay until the new download completes), a 416 for an already complete file is accepted, and the package is verified against its signature before installing; a resumed file that fails verification is discarded and downloaded again. Check and verification are cancellable, and obsolete checkpoints are removed.

Co-authored-by: kradme <[email protected]>
2026-11-26 17:03:02 +08:00
LU XIANGRUIтаwildcatDownstairs 89463afc18 fix(updates): show release notes on What's New after a Windows update (#6058)
After an in-app update on Windows, What's New always said the version had no release notes. The Windows installer ends the app inside appInstallUpdate, so the notes recorded after the call returned were never stored, and the fallback manifest read app_release_notes was trusted-only, which the project-less window the page opens in is refused. The notes are now recorded before the install starts and restored if the install fails or is cancelled, and app_release_notes is always allowed, like the update check: it reads only the public manifest.

Closes #6056

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 16:57:59 +08:00
Akbar Husainтаakbar1214 c884aa4cc6 fix(updates): cap updater connects so an unreachable CDN IP falls back (#5070)
The updater's HTTP client had no connect timeout, so an unreachable first address of the release CDN hostname held the update check until its 60 s deadline instead of falling through to the next address. The client now bounds connection setup (TCP and TLS) to 15 s, which reqwest divides across the resolved addresses.

Co-authored-by: akbar1214 <[email protected]>
2026-11-26 16:55:54 +08:00
Void Et Noxтаvoidetnox 09108e02e3 ci(release): publish the Homebrew cask to l0ng-ai/homebrew-tap (#5883)
After a stable release is published, a new homebrew job downloads both macOS DMGs, writes Casks/openidea.rb (per-arch SHA-256, auto_updates true so the in-app updater and brew upgrade don't fight, the openidea CLI as a binary, zap paths) and pushes it to l0ng-ai/homebrew-tap. It is skipped for prereleases and when HOMEBREW_TAP_TOKEN is unset, and can be run by hand for an existing tag. The README documents brew install --cask l0ng-ai/tap/openidea.

Co-authored-by: voidetnox <[email protected]>
2026-11-26 16:51:45 +08:00
Vladislav Kuzminтаprincipalwater 2b6ca90457 fix(ci): cache Maven plugins for Java build tests (#5966)
The Java build integration tests resolved maven-resources-plugin and maven-compiler-plugin from Maven Central on every run and failed when Central rate-limited the download. On GitHub-hosted runners CI now restores a dedicated local repository from cache, prepares it once with the shared jbuild-maven fixture (retrying 0/10/30 s, 5 minute limit) and saves it only after a successful preparation; both test crates use the same fixture POMs, so the cached plugins are the ones the tests need.

Closes #5964

Co-authored-by: principalwater <[email protected]>
2026-11-26 16:50:53 +08:00
audichuang 3c3681ef2b fix(clipboard): read the macOS clipboard natively for menu paste, without WebKit's Paste callout (#6061)
On macOS, WebKit asks the user to confirm execCommand("paste") and navigator.clipboard reads outside a paste event with a "Paste" callout. readClipboardPlainText fell back to navigator.clipboard.readText() whenever the native read found no text, and the terminal's menu Paste called execCommand("paste") and navigator.clipboard.read() before reading natively. On macOS a null from clipboard_text now means empty text (a refused command still falls back), and in the desktop app the terminal menu Paste reads files, text and images through the backend commands.

Co-authored-by: audichuang <[email protected]>
2026-11-26 16:42:19 +08:00
audichuang b0d7bfef24 fix(vcs): History for Selection no longer lists Local Changes when the newest commit is a merge (#6034)
History for Selection listed a Local Changes row on a clean file whenever the newest commit touching the selected lines was a merge: the list compared the current lines with the newest row's `after` block, and `git log -L` prints no patch for a merge, so that block was empty. The backend now returns HEAD's block (`BlockHistory.head`) and the list compares against it, falling back to the newest row for servers that predate the field.

Co-authored-by: audichuang <[email protected]>
2026-11-26 16:35:31 +08:00
l0ng-ai 527add030a fix(clipboard): read CF_UNICODETEXT pairs with as_chunks (#6126)
Clippy 1.100 adds chunks_exact_to_as_chunks, which failed the workspace clippy run on every PR. unicode_text now reads the UTF-16LE pairs of a CF_UNICODETEXT block with as_chunks::<2>(); behaviour is unchanged.
2026-11-26 16:32:29 +08:00
l0ng-ai 81c2fc9ace fix(vcs): scroll the changes tree horizontally instead of clipping rows (#6121)
Rows in the Commit and Local Changes trees were locked to the pane width and ellipsized, so the end of a long file name and its directory path could only be read by widening the tool window. The tree now keeps rows at their natural width and scrolls horizontally, as the Project view does.

Fixes #6080
2026-11-26 16:10:22 +08:00
38 змінених файлів з 1249 додано та 82 видалено

No files matched your search

+38
Переглянути файл
@@ -156,6 +156,44 @@ jobs:
- run: cargo clippy --workspace --all-targets -- -D warnings
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
- name: Prepare Maven artifacts for Java build tests
id: jbuild-maven
if: runner.environment == 'github-hosted'
timeout-minutes: 5
shell: bash
env:
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
run: |
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
exit 0
fi
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
for delay in 0 10 30; do
sleep "$delay"
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
done
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
- run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
+73
Переглянути файл
@@ -0,0 +1,73 @@
name: Homebrew
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
on:
workflow_call:
inputs:
tag: { type: string, required: true }
workflow_dispatch:
inputs:
tag:
description: "Published stable release to write the cask for (e.g. v0.1.51)"
required: true
permissions:
contents: read
concurrency:
group: homebrew-tap
jobs:
cask:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
TAG: ${{ inputs.tag }}
TAP: l0ng-ai/homebrew-tap
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
GH_TOKEN: ${{ github.token }}
steps:
- name: Check tag and token
id: check
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::notice::$TAG is not a stable release: the cask stays as is"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@v5
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
path: tap
- uses: actions/setup-node@v5
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
if: steps.check.outputs.skip != 'true'
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
- name: Write the cask
if: steps.check.outputs.skip != 'true'
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
- name: Push to the tap
if: steps.check.outputs.skip != 'true'
working-directory: tap
run: |
git add Casks/openidea.rb
if git diff --cached --quiet; then
echo "the cask is already at ${TAG#v}"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git commit -m "openidea ${TAG#v}"
git push
+7
Переглянути файл
@@ -178,3 +178,10 @@ jobs:
uses: ./.github/workflows/cnb-mirror.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
homebrew:
needs: publish
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
Створено
+1
Переглянути файл
@@ -6745,6 +6745,7 @@ dependencies = [
"objc2-web-kit 0.3.2",
"parking_lot",
"percent-encoding",
"reqwest",
"security-framework",
"serde",
"serde_json",
+6
Переглянути файл
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages. Builds for macOS, Windows and Linux.
On macOS you can also install it with Homebrew:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## Benchmark
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
+6
Переглянути файл
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
macOS'ta Homebrew ile de kurabilirsiniz:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## Performans karşılaştırması
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
+6
Переглянути файл
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
提供 macOS、Windows 和 Linux 版本。
在 macOS 上也可以用 Homebrew 安装:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## 性能对比
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
+3 -9
Переглянути файл
@@ -18,15 +18,9 @@ fn tools() -> Option<(PathBuf, PathBuf)> {
Some((home, mvn))
}
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
struct Fixture {
+24
Переглянути файл
@@ -0,0 +1,24 @@
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
</parent>
<artifactId>app</artifactId>
<dependencies>
<dependency>
<groupId>t</groupId>
<artifactId>lib</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
+9
Переглянути файл
@@ -0,0 +1,9 @@
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
</parent>
<artifactId>lib</artifactId>
</project>
+35
Переглянути файл
@@ -0,0 +1,35 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
<packaging>pom</packaging>
<modules>
<module>lib</module>
<module>app</module>
</modules>
<properties>
<maven.compiler.release>11</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.4.0</version>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
+2 -2
Переглянути файл
@@ -260,8 +260,8 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
/// may be larger than the text, and a malformed one may lack the NUL.
#[cfg(any(windows, test))]
fn unicode_text(bytes: &[u8]) -> String {
let units: Vec<u16> =
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
let (pairs, _) = bytes.as_chunks::<2>();
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
String::from_utf16_lossy(&units)
}
+3 -18
Переглянути файл
@@ -27,24 +27,9 @@ async fn maven_launch_compiles_with_the_ides_java_build() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(
&root,
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
);
write(
&root,
"lib/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
);
write(&root, "pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml"));
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
write(
&root,
"lib/src/main/java/l/L.java",
+9 -3
Переглянути файл
@@ -24,7 +24,7 @@ pub(crate) fn block_history(
crate::repo::blob_at(&repo, &rel, "HEAD")?
};
let Some(head) = head else {
return Ok(BlockHistory { head_lines: None, revisions: Vec::new() });
return Ok(BlockHistory { head_lines: None, head: None, revisions: Vec::new() });
};
let head = decode(&head, encoding);
let current = match current_text {
@@ -32,12 +32,18 @@ pub(crate) fn block_history(
None => decode(&std::fs::read(r.abs_path(&rel))?, encoding).into_owned(),
};
let Some((start, end)) = head_range(&crate::diff::line_hunks(&head, &current), lines) else {
return Ok(BlockHistory { head_lines: None, revisions: Vec::new() });
return Ok(BlockHistory { head_lines: None, head: None, revisions: Vec::new() });
};
let range = format!("-L{},{}:{rel}", start + 1, end + 1);
let args = ["log", "--no-color", "--no-ext-diff", "--no-textconv", FORMAT, &range, "HEAD"];
let out = cli::run_cancellable(r.root(), &args, cancel)?;
Ok(BlockHistory { head_lines: Some((start, end)), revisions: parse_log(&out.stdout, encoding) })
// The newest row's block can't stand in for HEAD's: a merge row has none.
let mut block = String::new();
for line in head.lines().skip(start as usize).take((end - start) as usize + 1) {
push_line(&mut block, line);
}
let revisions = parse_log(&out.stdout, encoding);
Ok(BlockHistory { head_lines: Some((start, end)), head: Some(block), revisions })
}
/// The HEAD lines (0-based, inclusive) of `lines` in the current text, given the
+3
Переглянути файл
@@ -139,6 +139,9 @@ pub struct BlameLine {
pub struct BlockHistory {
/// The selected lines in HEAD (0-based, inclusive); None when none of them is committed.
pub head_lines: Option<(u32, u32)>,
/// Those lines as HEAD has them, each ending with `\n`; None from servers that predate it.
#[serde(default)]
pub head: Option<String>,
pub revisions: Vec<BlockRevision>,
}
+23 -1
Переглянути файл
@@ -76,6 +76,8 @@ fn follows_the_block_through_edits_and_a_rename() {
let fx = renamed_history();
let h = history(&fx.repo(), &fx.path("b.txt"), None, (1, 2));
assert_eq!(h.head_lines, Some((1, 2)));
// Without a merge on top, HEAD's block is the newest row's.
assert_eq!(h.head.as_deref(), Some(h.revisions[0].after.as_str()));
let shown: Vec<_> = h.revisions.iter().map(|r| (r.summary.as_str(), r.path.as_str())).collect();
// Edits outside the block and the pure rename are left out.
assert_eq!(shown, [("Shout three", "b.txt"), ("Shout two", "a.txt"), ("Add a", "a.txt")]);
@@ -86,6 +88,26 @@ fn follows_the_block_through_edits_and_a_rename() {
assert!(newest.id.starts_with(&newest.short_id) && newest.time_ms > 0.0);
}
#[test]
fn newest_row_a_merge_without_a_diff() {
let fx = Fixture::new();
fx.write("a.txt", "a\nb\nc\nd\n");
fx.commit("Add a");
fx.git(&["switch", "-q", "-c", "side"]);
fx.write("a.txt", "A\nb\nc\nd\n");
fx.commit("Side edit");
fx.git(&["switch", "-q", "main"]);
fx.write("a.txt", "a\nb\nc\nD\n");
fx.commit("Main edit");
fx.git(&["merge", "-q", "--no-edit", "side"]);
let h = history(&fx.repo(), &fx.path("a.txt"), None, (0, 3));
let newest = &h.revisions[0];
assert!(newest.summary.starts_with("Merge"), "{newest:?}");
// Git prints no patch for the merge, so its block says nothing about HEAD.
assert_eq!((newest.before.as_str(), newest.after.as_str()), ("", ""));
assert_eq!(h.head.as_deref(), Some("A\nb\nc\nD\n"));
}
#[test]
fn maps_an_edited_selection_to_head_lines() {
let fx = renamed_history();
@@ -93,7 +115,7 @@ fn maps_an_edited_selection_to_head_lines() {
// Two unsaved lines inserted at the top: lines 3..=4 are HEAD's 1..=2.
let edited = "new\nnew\none\nTWO\nTHREE\nfour\nFIVE\n";
let h = history(&repo, &fx.path("b.txt"), Some(edited), (3, 4));
assert_eq!(h.head_lines, Some((1, 2)));
assert_eq!((h.head_lines, h.head.as_deref()), (Some((1, 2)), Some("TWO\nTHREE\n")));
assert_eq!(h.revisions.len(), 3);
// Only new lines selected, or a file Git does not know: nothing committed to show.
let h = history(&repo, &fx.path("b.txt"), Some(edited), (0, 1));
+47
Переглянути файл
@@ -0,0 +1,47 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { dmgName, renderCask, stableVersion } from "./homebrew-cask.ts";
const ARM = "5fc404ab470bb9ca5168ab5d1769ad5892d657a8992fb26adf192f2c60bd8279";
const INTEL = "38b3b06bbbc46503889ab43f16131f87037d3499cac7792e9fc221bcaac0bc05";
describe("stableVersion", () => {
it("takes the version of a stable tag", () => {
expect(stableVersion("v0.1.51")).toBe("0.1.51");
});
it("skips prereleases and other refs", () => {
expect(stableVersion("v0.2.0-beta.1")).toBeNull();
expect(stableVersion("0.1.51")).toBeNull();
expect(stableVersion("main")).toBeNull();
});
});
describe("dmgName", () => {
it("names the release's DMG of each arch", () => {
expect(dmgName("0.1.51", "arm")).toBe("OpenIDEA_0.1.51_aarch64.dmg");
expect(dmgName("0.1.51", "intel")).toBe("OpenIDEA_0.1.51_x64.dmg");
});
});
describe("renderCask", () => {
it("pins the version and the checksum of each arch", () => {
const cask = renderCask("0.1.51", { arm: ARM, intel: INTEL });
expect(cask).toContain(`version "0.1.51"`);
expect(cask).toContain(`sha256 arm: "${ARM}",\n intel: "${INTEL}"`);
expect(cask).toContain(
`url "https://github.com/l0ng-ai/openidea/releases/download/v#{version}/OpenIDEA_#{version}_#{arch}.dmg"`,
);
});
it("leaves updates to the app and installs the CLI", () => {
const cask = renderCask("0.1.51", { arm: ARM, intel: INTEL });
expect(cask).toContain("auto_updates true");
expect(cask).toContain(`binary "#{appdir}/OpenIDEA.app/Contents/Resources/bin/openidea"`);
expect(cask).toContain(`"~/Library/Application Support/ai.l0ng.openidea"`);
});
it("refuses a checksum that isn't SHA-256", () => {
expect(() => renderCask("0.1.51", { arm: ARM, intel: "abc" })).toThrow(/intel/);
});
});
+105
Переглянути файл
@@ -0,0 +1,105 @@
/**
* Writes the Homebrew cask for a published release:
* `node scripts/homebrew-cask.ts <tag> <dir> <out>`. `<dir>` holds the release's macOS DMGs
* (`gh release download <tag> -p '*.dmg'`); `<out>` is the cask file to write, e.g.
* `Casks/openidea.rb` in a checkout of the tap (l0ng-ai/homebrew-tap). The cask lets the app
* update itself (`auto_updates true`): the Tauri updater and `brew upgrade` don't fight.
*/
import { createHash } from "node:crypto";
import { createReadStream, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const GITHUB_REPO = "l0ng-ai/openidea";
const IDENTIFIER = "ai.l0ng.openidea";
/** The DMG of each Homebrew arch, as the release names it. */
export const DMG_ARCH = { arm: "aarch64", intel: "x64" } as const;
export interface Checksums {
arm: string;
intel: string;
}
/** The version of a stable release tag (`v0.1.51` → `0.1.51`); prereleases have none. */
export function stableVersion(tag: string): string | null {
const match = /^v(\d+\.\d+\.\d+)$/.exec(tag);
return match ? match[1]! : null;
}
export function dmgName(version: string, arch: keyof typeof DMG_ARCH): string {
return `OpenIDEA_${version}_${DMG_ARCH[arch]}.dmg`;
}
export function renderCask(version: string, sha256: Checksums): string {
for (const [arch, sum] of Object.entries(sha256)) {
if (!/^[0-9a-f]{64}$/.test(sum)) throw new Error(`${arch}: ${sum} is not a SHA-256`);
}
return `cask "openidea" do
arch arm: "${DMG_ARCH.arm}", intel: "${DMG_ARCH.intel}"
version "${version}"
sha256 arm: "${sha256.arm}",
intel: "${sha256.intel}"
url "https://github.com/${GITHUB_REPO}/releases/download/v#{version}/OpenIDEA_#{version}_#{arch}.dmg"
name "OpenIDEA"
desc "IDE inspired by IntelliJ IDEA, rebuilt in Rust"
homepage "https://openidea.sh/"
livecheck do
url :url
strategy :github_latest
end
auto_updates true
depends_on :macos
app "OpenIDEA.app"
binary "#{appdir}/OpenIDEA.app/Contents/Resources/bin/openidea"
zap trash: [
"~/Library/Application Support/${IDENTIFIER}",
"~/Library/Caches/${IDENTIFIER}",
"~/Library/HTTPStorages/${IDENTIFIER}",
"~/Library/Logs/${IDENTIFIER}",
"~/Library/Preferences/${IDENTIFIER}.plist",
"~/Library/Saved Application State/${IDENTIFIER}.savedState",
"~/Library/WebKit/${IDENTIFIER}",
]
end
`;
}
function sha256File(path: string): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash("sha256");
createReadStream(path)
.on("data", (chunk) => hash.update(chunk))
.on("error", reject)
.on("end", () => resolve(hash.digest("hex")));
});
}
async function main() {
const [tag, dir, out] = process.argv.slice(2);
if (!tag || !dir || !out) throw new Error("usage: node scripts/homebrew-cask.ts <tag> <dir> <out>");
const version = stableVersion(tag);
if (!version) throw new Error(`${tag} is not a stable release tag`);
const sum = async (arch: keyof typeof DMG_ARCH) => {
const path = join(dir, dmgName(version, arch));
if (!existsSync(path)) throw new Error(`${path} is missing`);
return sha256File(path);
};
const cask = renderCask(version, { arm: await sum("arm"), intel: await sum("intel") });
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, cask);
console.log(`wrote ${out} for OpenIDEA ${version}`);
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
main().catch((e) => {
console.error(e instanceof Error ? e.message : e);
process.exit(1);
});
}
+1
Переглянути файл
@@ -31,6 +31,7 @@ serde_json.workspace = true
base64.workspace = true
percent-encoding = "2"
tokio.workspace = true
reqwest.workspace = true
parking_lot.workspace = true
blake3.workspace = true
tracing.workspace = true
+69 -35
Переглянути файл
@@ -597,7 +597,19 @@ fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String>
}
}
fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
/// Bounds connection establishment (TCP and TLS) for the updater. reqwest divides this
/// across a host's resolved addresses, so a CDN hostname with four A records gets about
/// 3.75s each — enough for a slow link, while still leaving the 60s check budget intact.
const UPDATER_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
fn configure_updater_client(
builder: reqwest::ClientBuilder,
proxy: &ide_core::proxy_settings::ProxySettings,
) -> reqwest::ClientBuilder {
ide_http::client::with_proxy(builder, proxy).connect_timeout(UPDATER_CONNECT_TIMEOUT)
}
pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
use tauri_plugin_updater::UpdaterExt;
if !updates_configured(app) {
return Ok(None);
@@ -620,7 +632,7 @@ fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plug
builder = builder.target(target);
}
builder
.configure_client(move |b| ide_http::client::with_proxy(b, &proxy))
.configure_client(move |b| configure_updater_client(b, &proxy))
.endpoints(endpoints)
.map_err(|e| IdeError::invalid(e.to_string()))?
.build()
@@ -695,24 +707,23 @@ pub enum UpdateProgress {
/// Limits download events to one per whole percent (or per 256 KiB without a length).
#[derive(Default)]
struct ProgressThrottle {
downloaded: u64,
last_step: Option<u64>,
}
impl ProgressThrottle {
const UNKNOWN_STEP: u64 = 256 * 1024;
fn chunk(&mut self, len: usize, total: Option<u64>) -> Option<UpdateProgress> {
self.downloaded += len as u64;
/// Converts the downloader's absolute byte count into a throttled event.
fn report(&mut self, downloaded: u64, total: Option<u64>) -> Option<UpdateProgress> {
let step = match total {
Some(t) if t > 0 => self.downloaded.min(t) * 100 / t,
_ => self.downloaded / Self::UNKNOWN_STEP,
Some(t) if t > 0 => downloaded.min(t) * 100 / t,
_ => downloaded / Self::UNKNOWN_STEP,
};
if self.last_step == Some(step) {
return None;
}
self.last_step = Some(step);
Some(UpdateProgress::Downloading { downloaded: self.downloaded as f64, total: total.map(|t| t as f64) })
Some(UpdateProgress::Downloading { downloaded: downloaded as f64, total: total.map(|t| t as f64) })
}
}
@@ -750,28 +761,22 @@ pub async fn app_install_update(
InstallingGuard::acquire().ok_or_else(|| IdeError::unavailable("an update is already being installed"))?;
let token = state.host.begin_request(request);
let result = async {
let updater = updater(&app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let update = tokio::select! {
r = updater.check() => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
_ = token.cancelled() => return Err(IdeError::cancelled()),
}
.ok_or_else(|| IdeError::not_found("no update available"))?;
let mut throttle = ProgressThrottle::default();
let progress = on_progress.clone();
let download = update.download(
move |len, total| {
if let Some(p) = throttle.chunk(len, total) {
let downloaded = tokio::select! {
result = crate::updates::download_update(&app, source, &token, move |done, total| {
if let Some(p) = throttle.report(done, total) {
let _ = progress.send(p);
}
},
|| {},
);
let bytes = tokio::select! {
r = download => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
}) => result?,
_ = token.cancelled() => return Err(IdeError::cancelled()),
};
let crate::updates::DownloadedUpdate { update, bytes, path } = downloaded;
if token.is_cancelled() {
return Err(IdeError::cancelled());
}
let _ = on_progress.send(UpdateProgress::Installing);
tauri::async_runtime::spawn_blocking(move || {
let installed = tauri::async_runtime::spawn_blocking(move || {
#[cfg(windows)]
if update.target.ends_with("-portable") {
let exe = tauri::utils::platform::current_exe()?;
@@ -780,7 +785,11 @@ pub async fn app_install_update(
update.install(bytes).map_err(|e| IdeError::internal(e.to_string()))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(|e| IdeError::internal(e.to_string()))?;
if installed.is_ok() {
let _ = tokio::fs::remove_file(path).await;
}
installed
}
.await;
state.host.end_request(request);
@@ -793,7 +802,9 @@ pub async fn app_install_update(
/// can show the UI's language and fall back to English. An install records the
/// notes it saw, so this is only for an update installed outside the app.
/// `Ok(None)` when the manifest covers another version or carries no notes.
#[desktop_command(trust = trusted)]
/// Reads only the public manifest, like the update check: the page usually opens
/// in a window without a project.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn app_release_notes(
@@ -909,22 +920,33 @@ mod tests {
#[test]
fn throttle_reports_each_whole_percent_once() {
let mut t = ProgressThrottle::default();
assert_eq!(downloading(t.chunk(1, Some(1000))), Some((1.0, Some(1000.0))));
assert_eq!(downloading(t.chunk(5, Some(1000))), None);
assert_eq!(downloading(t.chunk(4, Some(1000))), Some((10.0, Some(1000.0))));
let reported = (0..99).filter(|_| t.chunk(10, Some(1000)).is_some()).count();
assert_eq!(reported, 99);
assert_eq!(t.downloaded, 1000);
assert_eq!(downloading(t.report(1, Some(1000))), Some((1.0, Some(1000.0))));
assert_eq!(downloading(t.report(9, Some(1000))), None);
assert_eq!(downloading(t.report(10, Some(1000))), Some((10.0, Some(1000.0))));
let reported = (11..=100).filter(|percent| t.report(percent * 10, Some(1000)).is_some()).count();
assert_eq!(reported, 90);
}
#[test]
fn throttle_without_length_reports_per_step() {
let mut t = ProgressThrottle::default();
assert!(t.chunk(10, None).is_some());
assert!(t.chunk(1024, None).is_none());
assert_eq!(downloading(t.chunk(256 * 1024, None)), Some(((256 * 1024 + 1034) as f64, None)));
assert!(t.report(10, None).is_some());
assert!(t.report(1024, None).is_none());
assert_eq!(downloading(t.report(256 * 1024 + 1034, None)), Some(((256 * 1024 + 1034) as f64, None)));
// A zero length is treated as unknown, not divided by.
assert!(ProgressThrottle::default().chunk(1, Some(0)).is_some());
assert!(ProgressThrottle::default().report(1, Some(0)).is_some());
}
#[test]
fn throttle_uses_absolute_bytes_after_a_full_download_restart() {
let mut t = ProgressThrottle::default();
let total = 100 * 1024 * 1024;
assert_eq!(downloading(t.report(40 * 1024 * 1024, None)), Some(((40 * 1024 * 1024) as f64, None)));
assert_eq!(downloading(t.report(1024, Some(total))), Some((1024.0, Some(total as f64))));
assert_eq!(
downloading(t.report(50 * 1024 * 1024, Some(total))),
Some(((50 * 1024 * 1024) as f64, Some(total as f64)))
);
}
#[test]
@@ -936,6 +958,18 @@ mod tests {
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
}
#[test]
fn updater_client_bounds_connection_setup() {
let proxy = ide_core::proxy_settings::ProxySettings::default();
let builder = configure_updater_client(reqwest::ClientBuilder::new(), &proxy);
// reqwest has no getter for this; its ClientBuilder Debug prints non-default settings.
let debug = format!("{builder:?}");
assert!(
debug.contains(&format!("connect_timeout: {:?}", UPDATER_CONNECT_TIMEOUT)),
"the updater must not wait forever on an unreachable CDN address: {debug}"
);
}
#[test]
fn only_one_install_at_a_time() {
let first = InstallingGuard::acquire().expect("first install starts");
+160 -2
Переглянути файл
@@ -1,16 +1,28 @@
//! Desktop updater coordination shared by all webviews.
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updates_configured};
mod download;
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updater, updates_configured};
use crate::state::AppState;
use ide_core::updates::{UpdateCheck, UpdatePolicy};
use ide_core::{IdeEvent, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult};
use parking_lot::Mutex;
use std::collections::HashSet;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use tauri::{AppHandle, Manager};
use tauri_plugin_updater::Update;
use tokio::sync::Notify;
/// One verified download, kept on disk until its installer has finished.
pub(crate) struct DownloadedUpdate {
pub update: Update,
pub bytes: Vec<u8>,
pub path: PathBuf,
}
/// Tauri patches the installer copies; the raw exe shipped in the portable zip keeps no bundle type.
pub fn portable_target(os: &str, arch: &str, bundle: Option<tauri::utils::config::BundleType>) -> Option<String> {
(os == "windows" && bundle.is_none()).then(|| format!("windows-{arch}-portable"))
@@ -129,6 +141,105 @@ pub async fn check(app: &AppHandle, source: Option<UpdateSource>) -> IdeResult<U
result
}
/// Downloads an update to a signature-keyed `.part` file, resuming from bytes
/// kept by a previous attempt or process, and verifies the completed package.
pub(crate) async fn download_update(
app: &AppHandle,
source: UpdateSource,
token: &CancellationToken,
mut progress: impl FnMut(u64, Option<u64>),
) -> IdeResult<DownloadedUpdate> {
let updater = updater(app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let update =
cancellable(token, async { updater.check().await.map_err(|error| IdeError::unavailable(error.to_string())) })
.await?
.ok_or_else(|| IdeError::not_found("no update available"))?;
let directory = app
.path()
.app_cache_dir()
.map_err(|error| IdeError::internal(format!("update cache directory: {error}")))?
.join("updates");
tokio::fs::create_dir_all(&directory).await?;
let key = cache_key(&update.version, &update.target, &update.signature);
let path = directory.join(format!("{key}.part"));
if let Err(error) = cleanup_stale_cache_files(&path).await {
tracing::warn!(%error, "cannot clean obsolete update downloads");
}
let client = ide_http::client::shared()?;
for attempt in 0..3 {
let outcome =
cancellable(token, download::fetch(&client, update.download_url.as_str(), &path, &mut progress)).await?;
match cancellable(token, verify_file(update.clone(), path.clone())).await {
Ok(bytes) => return Ok(DownloadedUpdate { update, bytes, path }),
Err(error) if outcome.resumed && attempt < 2 => {
tracing::warn!(%error, "discarding a mixed update checkpoint");
tokio::fs::remove_file(&path).await?;
}
Err(_) if outcome.total.is_none() && attempt < 2 => {
tracing::warn!("an update response of unknown length failed verification; resuming");
}
Err(error) => {
if outcome.resumed || outcome.total.is_some() {
tokio::fs::remove_file(&path).await?;
}
return Err(error);
}
}
}
Err(IdeError::internal("update download did not produce a verified package"))
}
/// Runs one fallible stage until it finishes or the command is cancelled. The
/// check and signature-verification stages previously escaped cancellation
/// while the download itself was cancellable.
async fn cancellable<T>(token: &CancellationToken, future: impl Future<Output = IdeResult<T>>) -> IdeResult<T> {
tokio::select! {
result = future => result,
_ = token.cancelled() => Err(IdeError::cancelled()),
}
}
/// Stable cache identity shared by GitHub and CNB for the same signed artifact.
fn cache_key(version: &str, target: &str, signature: &str) -> String {
let hash = blake3::hash(format!("{version}\0{target}\0{signature}").as_bytes()).to_hex();
format!("{version}-{target}-{hash}")
}
/// Reads and verifies a completed checkpoint on the blocking pool.
async fn verify_file(update: Update, path: PathBuf) -> IdeResult<Vec<u8>> {
tauri::async_runtime::spawn_blocking(move || {
let bytes = std::fs::read(path)?;
update.verify(&bytes).map_err(|error| IdeError::internal(error.to_string()))?;
Ok(bytes)
})
.await
.map_err(|error| IdeError::internal(error.to_string()))?
}
/// Keeps the current signed artifact's checkpoint and backup while removing
/// obsolete releases and abandoned fallback temporaries.
async fn cleanup_stale_cache_files(path: &Path) -> IdeResult<()> {
let Some(directory) = path.parent() else { return Ok(()) };
let keep_part = path.file_name();
let mut keep_backup = path.file_name().unwrap_or_default().to_os_string();
keep_backup.push(".backup");
let mut entries = tokio::fs::read_dir(directory).await?;
while let Some(entry) = entries.next_entry().await? {
if !entry.file_type().await?.is_file() {
continue;
}
let name = entry.file_name();
if Some(name.as_os_str()) == keep_part || name == keep_backup {
continue;
}
let text = name.to_string_lossy();
if text.ends_with(".part") || text.ends_with(".ready") || text.ends_with(".full") || text.ends_with(".backup") {
let _ = tokio::fs::remove_file(entry.path()).await;
}
}
Ok(())
}
fn emit_status(state: &AppState) {
let status = state.updates.state.lock().policy.status.clone();
state.sink.emit(IdeEvent::UpdateStatusChanged { status });
@@ -195,4 +306,51 @@ mod tests {
assert_eq!(ready_owner(Some("main"), &live, &HashSet::new()), None);
assert_eq!(ready_owner(Some("closed-window"), &[], &ready), None);
}
/// The cache identity stays stable across mirrors only while the signed bytes do.
#[test]
fn cache_identity_follows_the_signature_not_the_download_url() {
let first = cache_key("0.1.50", "darwin-aarch64", "signature-a");
assert_eq!(first, cache_key("0.1.50", "darwin-aarch64", "signature-a"));
assert_ne!(first, cache_key("0.1.50", "darwin-aarch64", "signature-b"));
assert_ne!(first, cache_key("0.1.51", "darwin-aarch64", "signature-a"));
}
/// Starting a download keeps its signed artifact's checkpoint and restores
/// its backup, while obsolete releases and fallback temporaries go away.
#[tokio::test]
async fn stale_update_cache_files_are_removed() {
let dir = tempfile::tempdir().unwrap();
let current = dir.path().join("current.part");
for name in
["current.part", "current.part.backup", "current.part.full", "old.part", "old.ready", "old.part.backup"]
{
tokio::fs::write(dir.path().join(name), b"x").await.unwrap();
}
tokio::fs::write(dir.path().join("unrelated.json"), b"{}").await.unwrap();
cleanup_stale_cache_files(&current).await.unwrap();
assert!(current.exists());
assert!(dir.path().join("current.part.backup").exists());
assert!(dir.path().join("unrelated.json").exists());
for name in ["current.part.full", "old.part", "old.ready", "old.part.backup"] {
assert!(!dir.path().join(name).exists(), "{name} was kept");
}
}
/// Signature verification is wrapped in the same cancellation boundary as
/// network work, so a late Cancel cannot fall through into installation.
#[tokio::test]
async fn cancelled_stage_stops_before_installation() {
let token = CancellationToken::new();
token.cancel();
let error = cancellable(&token, async {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(())
})
.await
.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
}
}
+338
Переглянути файл
@@ -0,0 +1,338 @@
//! Resumable update downloads for the existing install-and-restart flow.
use ide_core::{IdeError, IdeResult};
use reqwest::header::{ACCEPT, ACCEPT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, RANGE};
use reqwest::{Client, StatusCode};
use std::path::{Path, PathBuf};
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
/// How one request completed: whether it appended to the partial file, and
/// whether the response advertised a total size.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Outcome {
pub resumed: bool,
pub total: Option<u64>,
}
/// Appends `url` to `path`, resuming from its current length when the server
/// honours Range. An unsupported Range falls back to replacing the partial file
/// because installing bytes from different representations would be unsafe.
pub(crate) async fn fetch(
client: &Client,
url: &str,
path: &Path,
mut progress: impl FnMut(u64, Option<u64>),
) -> IdeResult<Outcome> {
let backup = beside(path, "backup");
if !path.exists() && backup.exists() {
tokio::fs::rename(&backup, path).await?;
} else if path.exists() {
let _ = tokio::fs::remove_file(backup).await;
}
let mut offset = match tokio::fs::metadata(path).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
loop {
progress(offset, None);
let mut request = client
.get(url)
.header(ACCEPT, "application/octet-stream")
// A byte offset is only meaningful for the representation the server
// advertised. Automatic content decoding would break that contract.
.header(ACCEPT_ENCODING, "identity");
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
let response = request.send().await.map_err(|error| IdeError::unavailable(error.to_string()))?;
let status = response.status();
if status == StatusCode::RANGE_NOT_SATISFIABLE && offset > 0 {
let total =
response.headers().get(CONTENT_RANGE).and_then(|value| value.to_str().ok()).and_then(unsatisfied_total);
if total == Some(offset) {
return Ok(Outcome { resumed: true, total });
}
tokio::fs::remove_file(path).await?;
offset = 0;
continue;
}
if status == StatusCode::PARTIAL_CONTENT {
let (start, total) = response
.headers()
.get(CONTENT_RANGE)
.and_then(|value| value.to_str().ok())
.and_then(partial_range)
.ok_or_else(|| IdeError::unavailable("update server sent an invalid Content-Range header"))?;
if start != offset {
// This is not the byte range we asked for. Keep the partial file:
// another mirror may resume it correctly, and this response is not
// safe to append.
return Err(IdeError::unavailable(format!(
"update server returned byte {start} while {offset} was requested"
)));
}
let mut file = OpenOptions::new().append(true).open(path).await?;
let downloaded = append_body(&mut file, response, offset, total, &mut progress).await?;
ensure_complete(downloaded, total)?;
return Ok(Outcome { resumed: offset > 0, total });
}
if status == StatusCode::OK {
let total = response
.headers()
.get(CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok());
if offset > 0 {
replace_with_full(response, path, total, &mut progress).await?;
} else {
let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path).await?;
let downloaded = append_body(&mut file, response, 0, total, &mut progress).await?;
ensure_complete(downloaded, total)?;
}
return Ok(Outcome { resumed: false, total });
}
return Err(IdeError::unavailable(format!("update download failed with HTTP {status}")));
}
}
/// Downloads a full response beside the existing partial file. The old bytes
/// stay resumable if the replacement connection fails before completion.
async fn replace_with_full(
response: reqwest::Response,
path: &Path,
total: Option<u64>,
progress: &mut impl FnMut(u64, Option<u64>),
) -> IdeResult<()> {
let temporary = beside(path, "full");
let backup = beside(path, "backup");
let result = async {
let mut file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&temporary)
.await
.map_err(IdeError::from)?;
let downloaded = append_body(&mut file, response, 0, total, progress).await?;
ensure_complete(downloaded, total)?;
let _ = tokio::fs::remove_file(&backup).await;
let had_old = path.exists();
if had_old {
tokio::fs::rename(path, &backup).await.map_err(IdeError::from)?;
}
if let Err(error) = tokio::fs::rename(&temporary, path).await {
if had_old {
let _ = tokio::fs::rename(&backup, path).await;
}
return Err(IdeError::from(error));
}
if had_old {
let _ = tokio::fs::remove_file(&backup).await;
}
Ok(())
}
.await;
if result.is_err() {
let _ = tokio::fs::remove_file(&temporary).await;
}
result
}
/// Returns a sibling of `path` whose name has `suffix` appended after its full
/// extension sequence, e.g. `update.part` and `full` → `update.part.full`.
fn beside(path: &Path, suffix: &str) -> PathBuf {
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(format!(".{suffix}"));
path.with_file_name(name)
}
/// Copies one response body into the persistent file and reports absolute
/// progress, including bytes recovered from an earlier process.
async fn append_body(
file: &mut tokio::fs::File,
mut response: reqwest::Response,
offset: u64,
total: Option<u64>,
progress: &mut impl FnMut(u64, Option<u64>),
) -> IdeResult<u64> {
let mut downloaded = offset;
while let Some(chunk) = response.chunk().await.map_err(|error| IdeError::unavailable(error.to_string()))? {
file.write_all(&chunk).await?;
downloaded += chunk.len() as u64;
progress(downloaded, total);
}
file.flush().await?;
file.sync_all().await?;
Ok(downloaded)
}
/// Rejects a body that ended before the advertised length instead of promoting
/// a truncated installer to the ready state.
fn ensure_complete(downloaded: u64, total: Option<u64>) -> IdeResult<()> {
match total {
Some(total) if downloaded != total => {
Err(IdeError::unavailable(format!("update download ended at {downloaded} of {total} bytes")))
}
_ => Ok(()),
}
}
/// Parses `bytes start-end/total`, returning the start and known total.
fn partial_range(value: &str) -> Option<(u64, Option<u64>)> {
let value = value.strip_prefix("bytes ")?;
let (range, total) = value.split_once('/')?;
let (start, _) = range.split_once('-')?;
let start = start.parse().ok()?;
let total = (total != "*").then(|| total.parse().ok()).flatten();
Some((start, total))
}
/// Parses the total from a `bytes */total` unsatisfied-range response.
fn unsatisfied_total(value: &str) -> Option<u64> {
value.strip_prefix("bytes */")?.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
/// Starts a one-request HTTP server and returns its URL plus the request line.
fn serve(response: Vec<u8>) -> (String, thread::JoinHandle<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let handle = thread::spawn(move || {
let (mut socket, _) = listener.accept().unwrap();
let mut request = Vec::new();
let mut byte = [0];
while !request.ends_with(b"\r\n\r\n") {
socket.read_exact(&mut byte).unwrap();
request.push(byte[0]);
}
socket.write_all(&response).unwrap();
String::from_utf8(request).unwrap()
});
(format!("http://{address}/update"), handle)
}
/// Builds a complete HTTP response with a fixed body.
fn http(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
let mut response = format!("HTTP/1.1 {status}\r\nConnection: close\r\n");
for (name, value) in headers {
response.push_str(&format!("{name}: {value}\r\n"));
}
response.push_str("\r\n");
response.into_bytes().into_iter().chain(body.iter().copied()).collect()
}
/// Drops a body early, then resumes from the bytes already on disk.
#[tokio::test]
async fn a_broken_download_resumes_with_range() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
let (url, first) = serve(http("200 OK", &[("Content-Length", "10")], b"abcd"));
assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err());
first.join().unwrap();
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"abcd");
let (url, second) = serve(http(
"206 Partial Content",
&[("Content-Range", "bytes 4-9/10"), ("Content-Length", "6")],
b"efghij",
));
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
let request = second.join().unwrap().to_ascii_lowercase();
assert!(request.contains("range: bytes=4-"), "{request}");
assert_eq!(outcome, Outcome { resumed: true, total: Some(10) });
assert_eq!(tokio::fs::read(path).await.unwrap(), b"abcdefghij");
}
/// Replaces a stale partial file when a proxy or mirror ignores Range.
#[tokio::test]
async fn a_full_response_after_a_partial_replaces_the_file() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(&path, b"stale").await.unwrap();
let (url, request) = serve(http("200 OK", &[("Content-Length", "7")], b"fresh!!"));
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=5-"));
assert_eq!(outcome, Outcome { resumed: false, total: Some(7) });
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"fresh!!");
assert!(!path.with_file_name("update.part.full").exists());
}
/// Keeps the older checkpoint when a proxy ignores Range and its full
/// replacement download breaks before completion.
#[tokio::test]
async fn a_broken_full_fallback_preserves_the_previous_partial() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(&path, b"stale").await.unwrap();
let (url, _) = serve(http("200 OK", &[("Content-Length", "10")], b"fresh"));
assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err());
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"stale");
assert!(!path.with_file_name("update.part.full").exists());
}
/// Accepts `bytes */length` as the only completion signal for an already
/// complete partial file after a process restart.
#[tokio::test]
async fn an_already_complete_partial_file_is_returned_on_416() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(&path, b"done").await.unwrap();
let (url, _) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */4")], b""));
assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: true, total: Some(4) });
}
/// A close-delimited response has no length to prove a clean EOF; the caller
/// uses this signal to resume instead of discarding a failed checkpoint.
#[tokio::test]
async fn a_close_delimited_response_reports_an_unknown_total() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
let (url, _) = serve(http("200 OK", &[], b"body"));
assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: false, total: None });
assert_eq!(tokio::fs::read(path).await.unwrap(), b"body");
}
/// A crash during the full-response swap leaves the old checkpoint in the
/// backup name; the next fetch restores it before calculating Range.
#[tokio::test]
async fn a_backup_checkpoint_is_restored_before_resuming() {
let client = ide_http::client::shared().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("update.part");
tokio::fs::write(beside(&path, "backup"), b"old").await.unwrap();
let (url, request) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */3")], b""));
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=3-"));
assert_eq!(outcome, Outcome { resumed: true, total: Some(3) });
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"old");
assert!(!beside(&path, "backup").exists());
}
/// Rejects malformed range metadata instead of appending to an unknown slice.
#[test]
fn content_range_parser_only_accepts_byte_ranges() {
assert_eq!(partial_range("bytes 4-9/10"), Some((4, Some(10))));
assert_eq!(partial_range("bytes 0-0/*"), Some((0, None)));
assert_eq!(partial_range("items 4-9/10"), None);
assert_eq!(unsatisfied_total("bytes */10"), Some(10));
assert_eq!(unsatisfied_total("bytes 0-1/10"), None);
}
}
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ app_install_update always desktop bin
app_log_location always desktop bindings sync
app_metrics always desktop bindings async
app_quit always desktop bindings sync
app_release_notes trusted desktop bindings async
app_release_notes always desktop bindings async
app_restart always desktop bindings sync
app_update_announcement always desktop bindings sync
app_update_status always desktop bindings sync
+4
Переглянути файл
@@ -227,6 +227,8 @@ export const commands = {
* can show the UI's language and fall back to English. An install records the
* notes it saw, so this is only for an update installed outside the app.
* `Ok(None)` when the manifest covers another version or carries no notes.
* Reads only the public manifest, like the update check: the page usually opens
* in a window without a project.
*/
appReleaseNotes: (version: string, source: UpdateSource) => typedError<{ [key in string]: string } | null, IdeError>(__TAURI_INVOKE("app_release_notes", { version, source })),
/** Quits through every window's unsaved-changes check, then starts again. */
@@ -3780,6 +3782,8 @@ export type BlameLine_Serialize = {
export type BlockHistory = {
/** The selected lines in HEAD (0-based, inclusive); None when none of them is committed. */
headLines: [number, number] | null,
/** Those lines as HEAD has them, each ending with `\n`; None from servers that predate it. */
head?: string | null,
revisions: BlockRevision[],
};
+16 -2
Переглянути файл
@@ -36,7 +36,8 @@ const appRestart = vi.fn(async () => null);
const cancelRequest = vi.fn(async () => null);
const appBuildInfo = vi.fn(async () => ({ version: "0.1.21" }));
const settingsSet = vi.fn(async () => ({ status: "ok", data: { general: {}, appearance: {} } }));
const recordInstalledUpdate = vi.fn();
const undoRecord = vi.fn();
const recordInstalledUpdate = vi.fn((_version: string, _notes: string | null) => undoRecord);
vi.mock("@/platform/releaseNotes", () => ({ recordInstalledUpdate }));
@@ -171,12 +172,24 @@ describe("Install and Restart", () => {
expect(appInstallUpdate).toHaveBeenCalledTimes(2);
});
it("records the notes before the install starts: the Windows installer ends the app inside it", async () => {
void installUpdate("0.1.22", "github", "## Fixed\n- a crash");
expect(appInstallUpdate).toHaveBeenCalledTimes(1);
expect(recordInstalledUpdate).toHaveBeenCalledWith("0.1.22", "## Fixed\n- a crash");
expect(recordInstalledUpdate.mock.invocationCallOrder[0]).toBeLessThan(
appInstallUpdate.mock.invocationCallOrder[0]!,
);
install.resolve(ok(null));
await tick();
expect(undoRecord).not.toHaveBeenCalled();
});
it("reports a failure with Retry, and a cancellation", async () => {
const failed = installUpdate("0.1.22");
install.resolve({ status: "error", error: { kind: "unavailable", message: "connection reset" } });
await failed;
expect(appRestart).not.toHaveBeenCalled();
expect(recordInstalledUpdate).not.toHaveBeenCalled();
expect(undoRecord).toHaveBeenCalledTimes(1);
expect(task(INSTALL_TASK_ID)?.done).toBe(true);
expect(notes.at(-1)).toMatchObject({
level: "error",
@@ -194,6 +207,7 @@ describe("Install and Restart", () => {
await cancelled;
expect(notes.at(-1)).toMatchObject({ level: "info", title: "Update cancelled", key: UPDATE_KEY });
expect(appRestart).not.toHaveBeenCalled();
expect(undoRecord).toHaveBeenCalledTimes(2);
});
it.each([
+4 -2
Переглянути файл
@@ -229,9 +229,13 @@ async function runInstall(version: string, source: UpdateSource, notes: string |
upsertTask({ id: INSTALL_TASK_ID, title, message: null, fraction: null, done: false, cancel });
// Replaces the notification whose action is now spent.
balloon([{ label: t("app.update.cancel"), run: cancel }]);
// The restarted app reads this to show the What's New page of the version it now runs.
// Recorded first: the Windows installer ends the app before the install returns.
const undoRecord = recordInstalledUpdate(version, notes);
try {
await call(commands.appInstallUpdate(source, request, channel));
} catch (e) {
undoRecord();
if (isCancelled(e)) {
notifications().notify({
level: "info",
@@ -257,8 +261,6 @@ async function runInstall(version: string, source: UpdateSource, notes: string |
} finally {
upsertTask({ id: INSTALL_TASK_ID, title, message: null, fraction: 1, done: true });
}
// The restarted app reads this to show the What's New page of the version it now runs.
recordInstalledUpdate(version, notes);
const restart = () => void commands.appRestart();
// Stays if a window cancels the restart (unsaved changes): the update applies on the next start.
notifications().notify({
+73 -1
Переглянути файл
@@ -13,6 +13,7 @@ beforeEach(() => {
notify.mockClear();
});
afterEach(() => {
usePlatform.setState({ os: "macos" });
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -181,6 +182,7 @@ function remoteTarget(current = () => true): TerminalPasteTarget {
}
it.each(["event", "menu"])("rejects oversized %s images before reading or uploading", async (route) => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
const read = vi.fn(async () => new ArrayBuffer(0));
const blob = image(read, 20 * 1024 * 1024 + 1);
const store = vi.spyOn(commands, "termStoreImage");
@@ -246,6 +248,7 @@ it("claims remote image events before xterm and pastes a quoted path only after
});
it("reads an image from the explicit paste menu after text and file recovery", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/stale.png"] });
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
const getType = vi.fn(async () => image());
@@ -261,6 +264,7 @@ it("reads an image from the explicit paste menu after text and file recovery", a
});
it("recovers remote menu file paths when image clipboard reading is unavailable", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/file.txt"] });
const store = vi.spyOn(commands, "termStoreImage");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "" } });
@@ -271,6 +275,7 @@ it("recovers remote menu file paths when image clipboard reading is unavailable"
});
it("uploads a menu image even if reading clipboard text is rejected", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
Object.defineProperty(navigator, "clipboard", {
configurable: true,
@@ -304,6 +309,7 @@ it("uploads image events instead of recovering a local image path", async () =>
});
it("does not upload a menu image when the target changes while reading", async () => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
let valid = true;
let finish!: (value: Blob) => void;
const getType = vi.fn(
@@ -446,6 +452,7 @@ function localTarget(shell = "sh", current = () => true): TerminalPasteTarget {
}
it.each(["event", "menu"])("stores raw local clipboard media through %s paste", async (route) => {
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/a'b c.png" });
const host = document.createElement("div");
const paste = vi.fn();
@@ -632,7 +639,7 @@ it.each([
{ os: "linux", native: "ls -la", expected: ["ls -la"], execCommand: 0 },
// An image-only clipboard keeps the WebView paths.
{ os: "linux", native: "", expected: [], execCommand: 1 },
{ os: "macos", native: "ls -la", expected: ["ls -la"], execCommand: 1 },
{ os: "macos", native: "ls -la", expected: ["ls -la"], execCommand: 0 },
] as const)("menu paste on $os with native text '$native'", async ({ os, native, expected, execCommand }) => {
usePlatform.setState({ os });
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: native });
@@ -651,3 +658,68 @@ it.each([
expect(exec).toHaveBeenCalledTimes(execCommand);
expect(paste.mock.calls).toEqual(expected.map((text) => [text]));
});
// WebKit on macOS shows a "Paste" callout for execCommand("paste") and navigator.clipboard reads
// outside a paste event: a menu paste reads text, files and images through the backend.
it.each([
{ name: "text", text: "ls -la", files: [], png: null, target: localTarget, expected: "ls -la" },
{
name: "Finder file",
text: "a b.txt",
files: ["/x/a b.txt"],
png: null,
target: localTarget,
expected: "'/x/a b.txt'",
},
{ name: "screenshot", text: null, files: [], png: "AQI=", target: localTarget, expected: "'/tmp/shot.png'" },
{ name: "remote screenshot", text: null, files: [], png: "AQI=", target: remoteTarget, expected: "'/tmp/shot.png'" },
{ name: "empty clipboard", text: null, files: [], png: null, target: localTarget, expected: null },
{
name: "remote file list",
text: "",
files: ["/x/a b.txt"],
png: null,
target: remoteTarget,
expected: "/x/a b.txt",
},
])("macOS menu paste of $name never asks WebKit", async ({ text, files, png, target, expected }) => {
usePlatform.setState({ os: "macos" });
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: text });
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: files });
vi.spyOn(commands, "clipboardImage").mockResolvedValue({
status: "ok",
data: png && `data:image/png;base64,${png}`,
});
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/shot.png" });
const web = { readText: vi.fn(async () => "web"), read: vi.fn(async () => []) };
Object.defineProperty(navigator, "clipboard", { configurable: true, value: web });
const exec = vi.fn(() => false);
Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: () => true });
Object.defineProperty(document, "execCommand", { configurable: true, value: exec });
const paste = vi.fn();
try {
await pasteTerminalClipboard(paste, () => target());
} finally {
Reflect.deleteProperty(document, "queryCommandSupported");
Reflect.deleteProperty(document, "execCommand");
}
expect(exec).not.toHaveBeenCalled();
expect(web.readText).not.toHaveBeenCalled();
expect(web.read).not.toHaveBeenCalled();
expect(paste.mock.calls).toEqual(expected ? [[expected]] : []);
if (png) expect(store).toHaveBeenCalledWith(42, png, "image/png");
expect(notify).not.toHaveBeenCalled();
});
it("keeps the WebView menu paste for a browser on macOS", async () => {
vi.unstubAllGlobals();
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType: async () => image() }] },
});
const paste = vi.fn();
await pasteTerminalClipboard(paste, () => remoteTarget());
expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png");
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
});
+24 -2
Переглянути файл
@@ -1,6 +1,6 @@
import { pasteClipboardFiles, readClipboardPlainText, readClipboardText } from "@/platform/clipboard";
import { pasteClipboardFiles, readClipboardPlainText, readClipboardPng, readClipboardText } from "@/platform/clipboard";
import { toBase64 } from "@/platform/base64";
import { call, commands, type TerminalId } from "@/platform/ipc";
import { call, commands, isTauri, type TerminalId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { usePlatform } from "@/platform/platformInfo";
import { notifications } from "@/workbench/contributions";
@@ -139,6 +139,28 @@ export async function pasteTerminalClipboard(paste: (text: string) => void, getT
return;
}
}
// WebKit on macOS asks the user to confirm execCommand("paste") and Clipboard.read() from a
// menu with a "Paste" callout; the backend reads files, text and images without asking.
if (target && isTauri() && usePlatform.getState().os === "macos") {
const paths: string[] = await call(commands.clipboardFileList()).catch(() => []);
const text =
paths.length && !target.remote ? pathsText(paths, target) : await readClipboardPlainText().catch(() => "");
if (!target.current()) return;
if (text) {
paste(text);
return;
}
const png = await readClipboardPng();
if (!target.current()) return;
if (png)
await pasteMedia(
new Blob([Uint8Array.from(atob(png), (c) => c.charCodeAt(0))], { type: "image/png" }),
target,
paste,
);
else if (paths.length) paste(paths.join("\n"));
return;
}
// Native paste preserves clipboard blobs where Clipboard.read() is unavailable.
if (target && document.queryCommandSupported?.("paste") && document.execCommand("paste")) return;
const images =
+1
Переглянути файл
@@ -1130,6 +1130,7 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
>
<Tree<ChangeNode>
handleRef={treeRef}
horizontalScroll
roots={roots}
getKey={(n) => n.key}
getLabel={nodeText}
+2 -1
Переглянути файл
@@ -37,7 +37,8 @@ export function blockOf(text: string, [from, to]: readonly [number, number]): st
/** The rows of the list: Local Changes when the block differs from HEAD, then the commits. */
export function historyRows(history: BlockHistory, current: string): HistoryRow[] {
const rows: HistoryRow[] = history.revisions.map((revision) => ({ kind: "revision", revision }));
const head = history.revisions[0]?.after;
// Servers that predate `head` only give the newest row's block, which a merge leaves empty.
const head = history.head ?? history.revisions[0]?.after;
if (history.headLines && head !== undefined && head !== current) rows.unshift({ kind: "local", head, current });
return rows;
}
+48
Переглянути файл
@@ -0,0 +1,48 @@
import { render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, call: vi.fn() };
});
vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
import { ChangesTree } from "../CommitView";
import { useVcs } from "../store";
import { useProject } from "@/platform/project";
const NAME = "some_long_service_implementation_with_a_very_long_name.ts";
describe("changes tree width (#6080)", () => {
beforeEach(() => {
localStorage.clear();
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
useVcs.setState({
root: "/p",
repo: "/p",
roots: ["/p"],
status: [
{
path: `/p/src/features/some_long_module_name/${NAME}`,
relPath: `src/features/some_long_module_name/${NAME}`,
staged: null,
unstaged: "modified" as const,
renamedFrom: null,
},
],
});
});
it.each(["commit", "local"] as const)("scrolls horizontally in %s mode instead of clipping rows", (mode) => {
render(<ChangesTree mode={mode} />);
const tree = screen.getByRole("tree", { name: "Changes" });
// The rows keep their natural width and the tree tracks the widest one for its scroll range.
expect(tree.querySelector("[data-content-width]")).not.toBeNull();
const row = screen.getByText(NAME).closest("[data-row]") as HTMLElement;
expect(row.className).toMatch(/wideRow/);
});
});
+12
Переглянути файл
@@ -92,6 +92,18 @@ describe("rows", () => {
expect(edited).toHaveLength(3);
expect(historyRows({ headLines: null, revisions: [] }, "new\n")).toEqual([]);
});
it("compares with HEAD's block, not the newest row, when that row is a merge without a diff", () => {
// `git log -L` prints no patch for a merge, so its row has empty sides.
const merge = revision("m", "Merge branch 'side'", "", "");
const merged: BlockHistory = { headLines: [1, 2], head: "TWO\nTHREE\n", revisions: [merge, ...history.revisions] };
expect(historyRows(merged, "TWO\nTHREE\n").map((r) => r.kind)).toEqual(["revision", "revision", "revision"]);
expect(historyRows(merged, "TWO\nTHREE!\n")[0]).toEqual({
kind: "local",
head: "TWO\nTHREE\n",
current: "TWO\nTHREE!\n",
});
});
});
describe("History for Selection tab", () => {
+25
Переглянути файл
@@ -1,7 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commands } from "./ipc";
import { usePlatform } from "./platformInfo";
import {
pasteClipboardFiles,
readClipboardPlainText,
readClipboardPng,
readClipboardText,
writeClipboardPng,
@@ -44,6 +46,29 @@ describe("clipboard text", () => {
expect(list).toHaveBeenCalledTimes(calls);
});
// WebKit on macOS asks the user to confirm navigator.clipboard reads outside a paste event.
it("treats no native text on macOS as empty, but falls back when the backend refuses", async () => {
usePlatform.setState({ os: "macos" });
const readText = vi.fn(async () => "web");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText } });
const native = vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: null });
expect(await readClipboardPlainText()).toBe("");
expect(readText).not.toHaveBeenCalled();
native.mockRejectedValue(new Error("restricted"));
expect(await readClipboardPlainText()).toBe("web");
});
it("falls back to the WebView where the backend has no text reader", async () => {
usePlatform.setState({ os: "windows" });
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "web" } });
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: null });
try {
expect(await readClipboardPlainText()).toBe("web");
} finally {
usePlatform.setState({ os: "macos" });
}
});
it("does not consult files for an empty text-only event or a browser", async () => {
const list = vi.spyOn(commands, "clipboardFileList");
expect(await readClipboardText(transfer("", false))).toBe("");
+4 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { call, commands, isTauri } from "./ipc";
import { ipcPath } from "./paths";
import { toBase64 } from "./base64";
import { usePlatform } from "./platformInfo";
/** Native menu actions and async work can outlive WebKit's user activation. */
export async function writeClipboardText(text: string): Promise<void> {
@@ -28,8 +29,10 @@ export async function writeClipboardPng(png: Promise<Blob>): Promise<void> {
*/
export async function readClipboardPlainText(): Promise<string> {
if (isTauri()) {
const text = await call(commands.clipboardText()).catch(() => null);
const text = await call(commands.clipboardText()).catch(() => undefined);
if (text != null) return text;
// WebKit on macOS makes the user confirm the read with a "Paste" callout; the backend found no text.
if (text === null && usePlatform.getState().os === "macos") return "";
}
return (await navigator.clipboard?.readText()) ?? "";
}
+33
Переглянути файл
@@ -712,3 +712,36 @@ describe(".icls schemes", () => {
}
});
});
describe("annotation colour (#6108)", () => {
const opt = (name: string, value: string) =>
`<option name="${name}"><value><option name="FOREGROUND" value="${value}"/></value></option>`;
const scheme = (parent: string | null, ...options: string[]) =>
parseIcls(
`<scheme name="A"${parent ? ` parent_scheme="${parent}"` : ""}><attributes>${options.join("")}</attributes></scheme>`,
).scheme;
it.each([
["Default", "#808000"],
["Darcula", "#bbb529"],
])("keeps %s's own annotation colour when the file only changes DEFAULT_METADATA", (parent, colour) => {
// IntelliJ shows Java annotations with the parent's ANNOTATION_NAME_ATTRIBUTES, not the file's default.
expect(scheme(parent, opt("DEFAULT_METADATA", "1d8711")).attributes.metadata?.foreground).toBe(colour);
});
it("takes the file's annotation key over its DEFAULT_METADATA", () => {
const s = scheme("Default", opt("DEFAULT_METADATA", "1d8711"), opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d"));
expect(s.attributes.metadata?.foreground).toBe("#9e880d");
});
it("uses DEFAULT_METADATA without a bundled parent", () => {
expect(scheme(null, opt("DEFAULT_METADATA", "1d8711")).attributes.metadata?.foreground).toBe("#1d8711");
});
it("exports the annotation colour under the annotation key, so it survives a re-import", () => {
const imported = scheme("Default", opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d"));
const xml = exportIcls("custom-a", { "custom-a": imported });
expect(xml).toContain('<option name="ANNOTATION_NAME_ATTRIBUTES">');
expect(parseIcls(xml).scheme.attributes.metadata?.foreground).toBe("#9e880d");
});
});
+8
Переглянути файл
@@ -40,6 +40,8 @@ const ATTRIBUTE_NAMES: Record<string, string> = {
DEFAULT_DOC_COMMENT_TAG: "docCommentTag",
DEFAULT_DOC_COMMENT_TAG_VALUE: "docCommentTagValue",
DEFAULT_DOC_MARKUP: "docCommentMarkup",
// Java's annotation key outranks the default it falls back to.
ANNOTATION_NAME_ATTRIBUTES: "metadata",
DEFAULT_METADATA: "metadata",
DEFAULT_OPERATION_SIGN: "operator",
DEFAULT_PARENTHS: "operator",
@@ -297,6 +299,8 @@ for (const id of [
// its fallback's. TypeScript keys win over JavaScript (TS.* falls back to JS.*), then Python, then the
// shared defaults; within a language, the key listed first above. DEFAULT_DOT, _COMMA and _SEMICOLON are
// not mapped: the one punctuation colour here would spread them to every brace and operator.
/** ANNOTATION_NAME_ATTRIBUTES as IntelliJ's bundled Default and Darcula schemes set it. */
const PARENT_ANNOTATIONS: Record<string, string> = { Default: "#808000", Darcula: "#bbb529" };
const KEY_ORDER = new Map(Object.keys(ATTRIBUTE_NAMES).map((name, i) => [name, i]));
const LANGUAGE_PRECEDENCE = ["TS.", "JS.", "PY."];
const precedence = (name: string) => {
@@ -488,6 +492,10 @@ export function parseIcls(
const own = new Set([...entries.keys()].flatMap((name) => (name ? targets(name) : [])));
for (const [id, value] of Object.entries(DARCULA_ATTRIBUTES)) if (!own.has(id)) attributes[id] ??= { ...value };
}
// Both bundled parents set Java's annotation key itself, so a file that leaves it out shows the parent's
// colour there, not its own DEFAULT_METADATA.
if (Object.hasOwn(PARENT_ANNOTATIONS, parentName) && !entries.has("ANNOTATION_NAME_ATTRIBUTES"))
attributes.metadata = { bold: false, italic: false, foreground: PARENT_ANNOTATIONS[parentName]! };
const bg = attributes.text?.background;
const rgb = bg ? [1, 3, 5].map((i) => parseInt(bg.slice(i, i + 2), 16)) : [255, 255, 255];
const dark = rgb[0]! * 0.299 + rgb[1]! * 0.587 + rgb[2]! * 0.114 < 128;
+10
Переглянути файл
@@ -57,4 +57,14 @@ describe("the notes' languages", () => {
expect(releaseNotesOf("0.1.40", "zh")).toBe("- older");
expect(recordedNotes("0.1.40")).toEqual({ text: "- older", texts: {} });
});
it("undo restores what an install that did not finish replaced", () => {
recordInstalledUpdate("0.1.40", "- current");
recordInstalledUpdate("0.1.41", "- next")();
expect(releaseNotesOf("0.1.40")).toBe("- current");
expect(releaseNotesOf("0.1.41")).toBeNull();
_resetReleaseNotesForTests();
recordInstalledUpdate("0.1.41", "- next")();
expect(releaseNotesOf("0.1.41")).toBeNull();
});
});
+16 -2
Переглянути файл
@@ -38,22 +38,36 @@ function read(): Stored | null {
}
}
/** Called once an update installed, with the notes its manifest carried. */
/**
* Called before an update installs, with the notes its manifest carried: on
* Windows the installer ends the app inside the install, so nothing after it runs.
* Returns an undo that restores what was stored, for an install that fails or is cancelled.
*/
export function recordInstalledUpdate(
version: string,
notes: string | null,
translations: Record<string, string> | null = null,
): void {
): () => void {
const text = notes?.trim();
const texts = Object.fromEntries(
Object.entries(translations ?? {}).filter(([lang, t]) => lang && lang !== DEFAULT_LOCALE && t.trim()),
);
let previous: string | null = null;
try {
previous = globalThis.localStorage?.getItem(KEY) ?? null;
if (text) globalThis.localStorage?.setItem(KEY, JSON.stringify({ version, text, texts }));
else globalThis.localStorage?.removeItem(KEY);
} catch {
/* storage unavailable: the page reads the manifest instead */
}
return () => {
try {
if (previous === null) globalThis.localStorage?.removeItem(KEY);
else globalThis.localStorage?.setItem(KEY, previous);
} catch {
/* storage unavailable */
}
};
}
/** Notes recorded when this version was installed, for the page to pick the UI's language from. */