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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 5fb2988f69 fix(agents): anchor composer completions below the caret 2026-10-29 19:42:26 +08:00
l0ng-ai 74b2d5f5d7 fix(vcs): prevent Git log refresh flicker and graph seams (#269) 2026-10-29 19:12:31 +08:00
l0ng-ai 297b15a7b1 fix(agents): expose Cursor approval controls (#265) 2026-10-29 19:12:27 +08:00
l0ng-ai 97144421d2 fix(agents): open local file links in Markdown messages (#263) 2026-10-29 19:12:23 +08:00
JawтаClaude Opus 5.5 200ed6a528 fix(project): paste files copied in Finder on macOS (#250)
The OS clipboard's file list was only wired up for Windows (CF_HDROP), so on
macOS the project view never saw files copied in Finder: Paste stayed disabled
and ⌘V did nothing. Read and write the general NSPasteboard's file URLs
instead, so Finder's copies paste into the project view and the project view's
copies paste in Finder.

Closes #246

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-29 18:05:11 +08:00
l0ng-ai 4666c4b9a5 fix(settings): keep macOS settings visible across displays (#254) 2026-10-29 18:05:06 +08:00
JawтаClaude Opus 5.5 ce43a7aa70 chore: add pre-commit hook with simple-git-hooks and lint-staged (#252)
Run oxlint --fix and oxfmt on staged files before each commit, and
rustfmt on staged Rust files. simple-git-hooks installs the hook from
its postinstall, allowed in pnpm-workspace.yaml.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-29 17:47:55 +08:00
l0ng-ai f911196f7d ci(release): Write latest.json once after every build (#176)
Each build's tauri-action rewrote the shared latest.json by deleting and re-uploading it, so
parallel macOS builds raced: one failed with 404 on the delete (skipping DMG notarization), or a
platform could silently drop out of the manifest. The builds no longer upload it; a new
updater-manifest job builds it once from the uploaded .sig files and fails if any platform is
missing. publish waits for it.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
2026-10-29 17:47:47 +08:00
26 змінених файлів з 733 додано та 105 видалено

No files matched your search

+60 -1
Переглянути файл
@@ -117,6 +117,8 @@ jobs:
releaseId: ${{ needs.create-release.outputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
uploadUpdaterJson: false
# tauri-action notarizes the .app but not the DMG around it; notarize and
# staple the DMG too, then replace the uploaded asset.
- name: Notarize DMG
@@ -172,8 +174,65 @@ jobs:
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
# Fails when a platform is missing, so a release never ships a manifest without it.
updater-manifest:
needs: [create-release, build]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
script: |
const { owner, repo } = context.repo;
const release_id = Number(process.env.RELEASE_ID);
const tag = process.env.TAG;
const assets = await github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id });
const sigs = assets.filter((a) => a.name.endsWith(".sig"));
if (sigs.length === 0) {
core.notice("no signed bundles (TAURI_SIGNING_PRIVATE_KEY unset): skipping latest.json");
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
const kinds = [
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
[/_x64_en-US\.msi$/, ["windows-x86_64", "windows-x86_64-msi"]],
[/_x64-setup\.exe$/, ["windows-x86_64-nsis"]],
];
const platforms = {};
for (const sig of sigs) {
const bundle = sig.name.slice(0, -".sig".length);
const kind = kinds.find(([re]) => re.test(bundle));
if (!kind) continue;
const { data } = await github.rest.repos.getReleaseAsset({
owner, repo, asset_id: sig.id, headers: { accept: "application/octet-stream" },
});
const signature = Buffer.from(data).toString("utf8").trim();
const url = `https://github.com/${owner}/${repo}/releases/download/${tag}/${encodeURIComponent(bundle)}`;
for (const key of kind[1]) platforms[key] = { signature, url };
}
const missing = kinds.flatMap(([, keys]) => keys).filter((k) => !platforms[k]);
if (missing.length) {
core.setFailed(`latest.json would miss ${missing.join(", ")}`);
return;
}
const manifest = { version: tag.replace(/^v/, ""), notes: "", pub_date: new Date().toISOString(), platforms };
const old = assets.find((a) => a.name === "latest.json");
if (old) await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id });
await github.rest.repos.uploadReleaseAsset({
owner, repo, release_id, name: "latest.json",
data: JSON.stringify(manifest, null, 2),
headers: { "content-type": "application/json" },
});
core.info(`latest.json: ${Object.keys(platforms).sort().join(", ")}`);
publish:
needs: [create-release, build, server]
needs: [create-release, build, server, updater-manifest]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
Створено
+5
Переглянути файл
@@ -4025,6 +4025,11 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.24"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
[[package]]
name = "ide-core"
+34 -1
Переглянути файл
@@ -4,6 +4,39 @@
use crate::model::{AgentCommand, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentUsage};
use serde_json::{Value, json};
/// Cursor exposes execution modes over ACP, but leaves approval policy to its client.
pub(crate) const CURSOR_APPROVAL: &str = "openidea.cursor.approval";
pub(crate) fn add_client_options(provider: &str, config: &mut Vec<AgentConfigOption>) {
if provider != "cursor" || config.iter().any(|o| o.id == CURSOR_APPROVAL) {
return;
}
config.push(AgentConfigOption {
id: CURSOR_APPROVAL.into(),
name: "Approvals".into(),
description: Some("Tool approvals for this Cursor conversation".into()),
category: Some("approval".into()),
current: Some("ask".into()),
via: AgentConfigVia::Option,
values: vec![
AgentConfigValue {
value: "ask".into(),
name: "Ask for approval".into(),
description: Some("Show permission requests from Cursor".into()),
},
AgentConfigValue {
value: "bypass".into(),
name: "Bypass approvals".into(),
description: Some("Automatically approve tool requests in this conversation".into()),
},
],
});
}
pub(crate) fn bypass_approvals(provider: &str, config: &[AgentConfigOption]) -> bool {
provider == "cursor" && config.iter().any(|o| o.id == CURSOR_APPROVAL && o.current.as_deref() == Some("bypass"))
}
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
/// plus the older `modes` / `models` fields for what those don't cover.
pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
@@ -64,7 +97,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) {
let fresh = parse_options(options);
let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category);
config.retain(|o| o.via != AgentConfigVia::Option && !covered(o));
config.retain(|o| o.id == CURSOR_APPROVAL || (o.via != AgentConfigVia::Option && !covered(o)));
let legacy = std::mem::take(config);
config.extend(fresh);
config.extend(legacy);
+36 -4
Переглянути файл
@@ -114,7 +114,13 @@ impl Shared {
}
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default()
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
config::add_client_options(provider, &mut config);
// Approval bypass belongs to the conversation, never to another new task.
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
o.current = Some("ask".into());
}
config
}
/// The commands the agent offered last time in this project.
@@ -516,7 +522,7 @@ impl AgentManager {
o.clone()
};
let live = task.live.lock().clone().filter(|l| !l.peer.is_closed());
if let Some(live) = live {
if let Some(live) = live.filter(|_| option != config::CURSOR_APPROVAL) {
let (method, mut params) = config::set_request(&target, &value);
params["sessionId"] = json!(live.session);
let reply: Value =
@@ -534,6 +540,7 @@ impl AgentManager {
}
s.task.model = model_of(&s.task.config).or(s.task.model.take());
}
task.approve_pending();
task.persist();
task.emit_task();
Ok(())
@@ -789,7 +796,8 @@ impl AgentManager {
impl Task {
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let task = file.task;
let mut task = file.task;
config::add_client_options(&task.provider, &mut task.config);
let conversation = Conversation::restore(file.entries, file.subagents);
Arc::new(Self {
id: task.id.clone(),
@@ -1174,10 +1182,17 @@ impl Task {
let s = self.state.lock();
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
};
config::add_client_options(&provider_id, &mut options);
self.shared.remember(&provider_id, Some(&options), None);
for choice in &wanted {
// An option the session doesn't offer yet is set once it does (`apply_late_choices`).
let Some(o) = options.iter().find(|o| o.id == choice.id).cloned() else { continue };
if o.id == config::CURSOR_APPROVAL {
if o.values.iter().any(|v| v.value == choice.value) {
options.iter_mut().find(|o| o.id == choice.id).unwrap().current = Some(choice.value.clone());
}
continue;
}
let already = known && o.current.as_deref() == Some(choice.value.as_str());
if already || !o.values.iter().any(|v| v.value == choice.value) {
continue;
@@ -1221,7 +1236,7 @@ impl Task {
s.wanted
.iter()
.filter_map(|c| {
let o = s.task.config.iter().find(|o| o.id == c.id)?;
let o = s.task.config.iter().find(|o| o.id == c.id && o.id != config::CURSOR_APPROVAL)?;
let due = o.current.as_deref() != Some(c.value.as_str())
&& o.values.iter().any(|v| v.value == c.value)
&& sent.insert((c.id.clone(), c.value.clone()));
@@ -1400,6 +1415,7 @@ impl Task {
let entry = self.push_entry(AgentEntry::Permission { id, title, options: options.clone(), chosen: None });
self.permissions.lock().insert(id, tx);
self.set_status(AgentStatus::NeedsInput, None);
self.approve_pending();
let answer = rx.recv().ok().flatten();
let name = answer
@@ -1423,6 +1439,22 @@ impl Task {
}
}
fn approve_pending(&self) {
let s = self.state.lock();
if self.cancel_pending.load(Ordering::Acquire) || !config::bypass_approvals(&s.task.provider, &s.task.config) {
return;
}
let mut pending = self.permissions.lock();
for entry in s.conversation.main.entries.iter().rev() {
if let AgentEntry::Permission { id, options, chosen: None, .. } = entry
&& let Some(option) = options.iter().find(|o| o.kind == "allow_once")
&& let Some(reply) = pending.remove(id)
{
let _ = reply.send(Some(option.id.clone()));
}
}
}
fn cancel_permissions(&self) {
for (_, reply) in self.permissions.lock().drain() {
let _ = reply.send(None);
+61
Переглянути файл
@@ -720,3 +720,64 @@ fn retry_updates_become_a_countdown() {
);
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let new = || NewAgentTask {
prompt: text("Fix"),
provider: "cursor".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
};
let task = mgr.create(new()).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "bypass".into()).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(
mgr.entries(&task.id, None)
.unwrap()
.iter()
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow"))
);
// Agent config updates must not erase the client's approval setting.
mgr.prompt(&task.id, text("late option"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let t = mgr.task(&task.id).unwrap();
assert!(config::bypass_approvals("cursor", &t.state.lock().task.config));
t.kill();
mgr.prompt(&task.id, text("Fix again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|c| c.contains("bypass")));
assert!(!config::bypass_approvals("cursor", &mgr.shared.known_config("cursor")));
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "ask".into()).await.unwrap();
mgr.prompt(&task.id, text("Fix once more"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
// An unrelated new conversation still asks, even after the cache was updated.
let other = mgr.create(new()).await.unwrap();
wait_for(&mgr, &other.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("Fix"),
provider: "cursor".into(),
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
}
+6 -1
Переглянути файл
@@ -1,8 +1,13 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP read/write, no window or message loop"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6", default-features = false, features = ["std"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
+78 -4
Переглянути файл
@@ -7,9 +7,12 @@
//! in full rather than rendered on demand, so no window or message loop is
//! needed and the list survives after `CloseClipboard`.
//!
//! Other platforms keep file lists elsewhere (`public.file-url` on macOS,
//! `text/uri-list` on X11) and are not wired up: [`files`] is empty and
//! [`set_files`] fails there.
//! macOS keeps one `public.file-url` item per file on the general
//! `NSPasteboard`; `NSURL` reads and writes them, so Finder's copies paste here
//! and ours paste in Finder.
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
use std::path::PathBuf;
@@ -218,7 +221,78 @@ mod imp {
}
}
#[cfg(not(windows))]
#[cfg(target_os = "macos")]
mod imp {
use objc2::ClassType;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2_app_kit::{
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSURL};
use std::path::PathBuf;
/// `NSURL` as the one class to read, limited to file URLs: a web link the
/// user copied is not a file to paste.
fn read_file_urls<R>(
f: impl FnOnce(&NSPasteboard, &NSArray<AnyClass>, &NSDictionary<NSPasteboardReadingOptionKey, AnyObject>) -> R,
) -> R {
autoreleasepool(|_| {
let board = NSPasteboard::generalPasteboard();
let classes = NSArray::from_slice(&[NSURL::class()]);
let yes = NSNumber::new_bool(true);
// SAFETY: the key is an AppKit constant, valid for the process' lifetime.
let key = unsafe { NSPasteboardURLReadingFileURLsOnlyKey };
let options = NSDictionary::from_slices(&[key], &[yes.as_ref() as &AnyObject]);
f(&board, &classes, &options)
})
}
pub fn has_files() -> bool {
// SAFETY: the class list holds `NSURL`, which reads from pasteboards,
// and the option takes an `NSNumber`.
read_file_urls(|board, classes, options| unsafe {
board.canReadObjectForClasses_options(classes, Some(options))
})
}
pub fn files() -> Vec<PathBuf> {
read_file_urls(|board, classes, options| {
// SAFETY: as in `has_files`; every object read for `NSURL` is one.
let Some(objects) = (unsafe { board.readObjectsForClasses_options(classes, Some(options)) }) else {
return Vec::new();
};
objects
.iter()
.filter_map(|object| object.downcast::<NSURL>().ok())
.filter_map(|url| url.to_file_path())
// Finder ends a folder's URL in `/`; the project view names it without.
.map(|path| path.components().collect())
.collect()
})
}
pub fn set_files(paths: &[PathBuf]) -> bool {
autoreleasepool(|_| {
// Folders get a directory URL (ending in `/`), as Finder writes them.
let urls: Vec<Retained<NSURL>> = paths
.iter()
.filter_map(|p| if p.is_dir() { NSURL::from_directory_path(p) } else { NSURL::from_file_path(p) })
.collect();
if urls.is_empty() {
return false;
}
let writers: Vec<&ProtocolObject<dyn NSPasteboardWriting>> =
urls.iter().map(|url| ProtocolObject::from_ref(&**url)).collect();
let board = NSPasteboard::generalPasteboard();
// Replacing the list also drops the text the user copied before.
board.clearContents();
board.writeObjects(&NSArray::from_slice(&writers))
})
}
}
#[cfg(not(any(windows, target_os = "macos")))]
mod imp {
use std::path::PathBuf;
+10
Переглянути файл
@@ -24,6 +24,14 @@
"perf": "node perf/run.ts",
"perf:rust": "node perf/rust.ts"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
},
"lint-staged": {
"*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}": "oxlint --fix --no-error-on-unmatched-pattern",
"*": "oxfmt --no-error-on-unmatched-pattern",
"*.rs": "rustfmt --edition 2024"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
@@ -71,8 +79,10 @@
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^6.0.2",
"jsdom": "^30.1.3",
"lint-staged": "^17.6.0",
"oxfmt": "^0.74.0",
"oxlint": "^1.89.0",
"simple-git-hooks": "^2.14.0",
"tsrs": "^0.20.0-ts7.1.0-beta",
"typescript": "~6.0.3",
"vite": "^8.0.16",
Створено
+54 -14
Переглянути файл
@@ -116,7 +116,7 @@ importers:
version: 2.12.3
'@testing-library/jest-dom':
specifier: ^7.0.1
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])))
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))
'@testing-library/react':
specifier: ^16.3.3
version: 16.3.3(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
@@ -137,16 +137,22 @@ importers:
version: 19.3.0(@types/[email protected])
'@vitejs/plugin-react':
specifier: ^6.0.2
version: 6.1.2([email protected](@types/[email protected]))
version: 6.1.2([email protected](@types/[email protected])([email protected]))
jsdom:
specifier: ^30.1.3
version: 30.1.3
lint-staged:
specifier: ^17.6.0
version: 17.6.0
oxfmt:
specifier: ^0.74.0
version: 0.74.0
oxlint:
specifier: ^1.89.0
version: 1.89.0
simple-git-hooks:
specifier: ^2.14.0
version: 2.14.0
tsrs:
specifier: ^0.20.0-ts7.1.0-beta
version: 0.20.0-ts7.1.0-beta
@@ -155,10 +161,10 @@ importers:
version: 6.0.3
vite:
specifier: ^8.0.16
version: 8.3.4(@types/[email protected])
version: 8.3.4(@types/[email protected])([email protected])
vitest:
specifier: ^5.0.5
version: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected]))
version: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))
packages:
@@ -1581,6 +1587,11 @@ packages:
resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
engines: {node: '>= 12.0.0'}
[email protected]:
resolution: {integrity: sha512-nOhBfYkZEwkFtNzD5pK9s9LkcWoxJ+whLzEnhqi9nl7zTB5n7tg8+9iYgMGx2Wm3VlLu8cbNj0RACzY+nWi5iQ==}
engines: {node: '>=22.22.1'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}
@@ -1748,6 +1759,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}
[email protected]:
resolution: {integrity: sha512-kkTORPAuxQz2g1QUuN0J8yGWT28tjGBfPOdJ4xT7Vbeu30veKUZQIoID2qGgCDAakaQn59UeZJJ4cFGB8PVP2A==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
@@ -1755,6 +1770,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}
[email protected]:
resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
engines: {node: '>=0.6.19'}
[email protected]:
resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
engines: {node: '>=8'}
@@ -1936,6 +1955,11 @@ packages:
[email protected]:
resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
[email protected]:
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
engines: {node: '>= 14.6'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==}
engines: {node: '>=12.20.0'}
@@ -2698,7 +2722,7 @@ snapshots:
picocolors: 1.1.1
pretty-format: 27.5.1
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])))':
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))':
dependencies:
'@adobe/css-tools': 4.5.0
'@testing-library/dom': 10.4.2
@@ -2708,7 +2732,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
vitest: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected]))
vitest: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))
'@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':
dependencies:
@@ -2899,19 +2923,19 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
'@vitejs/[email protected]([email protected](@types/[email protected]))':
'@vitejs/[email protected]([email protected](@types/[email protected])([email protected]))':
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.3.4(@types/[email protected])
vite: 8.3.4(@types/[email protected])([email protected])
'@vitest/[email protected]([email protected](@types/[email protected]))':
'@vitest/[email protected]([email protected](@types/[email protected])([email protected]))':
dependencies:
'@jridgewell/trace-mapping': 0.3.31
'@vitest/spy': 5.0.5
estree-walker: 3.0.3
magic-string: 1.4.3
optionalDependencies:
vite: 8.3.4(@types/[email protected])
vite: 8.3.4(@types/[email protected])([email protected])
'@vitest/[email protected]': {}
@@ -3331,6 +3355,14 @@ snapshots:
lightningcss-win32-arm64-msvc: 1.33.0
lightningcss-win32-x64-msvc: 1.33.0
[email protected]:
dependencies:
picomatch: 4.0.7
string-argv: 0.3.2
tinyexec: 1.3.1
optionalDependencies:
yaml: 2.9.1
[email protected]: {}
[email protected]: {}
@@ -3525,10 +3557,14 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
min-indent: 1.0.1
@@ -3582,7 +3618,7 @@ snapshots:
[email protected]: {}
[email protected](@types/[email protected]):
[email protected](@types/[email protected])([email protected]):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
@@ -3592,11 +3628,12 @@ snapshots:
optionalDependencies:
'@types/node': 26.6.5
fsevents: 2.3.3
yaml: 2.9.1
[email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])):
[email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.5([email protected](@types/[email protected]))
'@vitest/mocker': 5.0.5([email protected](@types/[email protected])([email protected]))
chai: 6.3.0
es-module-lexer: 2.3.2
expect-type: 1.4.0
@@ -3607,7 +3644,7 @@ snapshots:
tinybench: 6.2.2
tinyexec: 1.3.1
tinyglobby: 0.2.17
vite: 8.3.4(@types/[email protected])
vite: 8.3.4(@types/[email protected])([email protected])
why-is-node-running: 3.2.1
optionalDependencies:
'@types/node': 26.6.5
@@ -3639,6 +3676,9 @@ snapshots:
[email protected]: {}
[email protected]:
optional: true
[email protected](@types/[email protected])([email protected])([email protected]):
optionalDependencies:
'@types/react': 19.3.0
+2
Переглянути файл
@@ -0,0 +1,2 @@
allowBuilds:
simple-git-hooks: true
+9 -5
Переглянути файл
@@ -6,7 +6,7 @@
//! (`window_take_launch`), and re-taken whenever [`LAUNCH_EVENT`] fires (a
//! second app instance asking an already-loaded window to open a path).
//!
//! Settings open in a native child window `settings-<parent>` (one per project
//! Settings open in a separate window `settings-<parent>` (one per project
//! window) that shares its parent's project (see [`AppState::project`]); its
//! [`Launch::settings_page`] tells it which page to show.
@@ -666,7 +666,7 @@ pub fn cycle(app: &AppHandle, current: &str, forward: bool) {
}
/// Opens (or focuses) the settings window of `parent` showing `page`: a
/// native child window centred over its parent, sized like IDEA's Settings.
/// separate window centred over its parent, sized like IDEA's Settings.
pub fn open_settings_window(
app: &AppHandle,
parent: &WebviewWindow,
@@ -699,13 +699,17 @@ pub fn open_settings_window(
config.maximized = false;
config.fullscreen = false;
config.drag_drop_enabled = false;
// macOS shows a child window as soon as it is attached, before the page loads: paint the theme's frame colour.
// Paint the theme's frame colour before the page loads.
if let Some(color) = background.as_deref().and_then(hex_color) {
config.background_color = Some(color);
}
windows.set_launch(&label, Launch { settings_page: page, new_projects, ..Default::default() });
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| b.parent(&parent))
let builder = WebviewWindowBuilder::from_config(app, &config);
// AppKit child windows can disappear when dragged to another display's Space.
// The settings label already tracks ownership and parent-close cleanup.
#[cfg(not(target_os = "macos"))]
let builder = builder.and_then(|b| b.parent(&parent));
let window = builder
.and_then(|b| b.build())
.map_err(|e| IdeError::internal(format!("cannot create settings window: {e}")))?;
apply_zoom(app, &window);
+16 -11
Переглянути файл
@@ -98,21 +98,26 @@
opacity: 1;
}
/* `@` / `/` completion, above the box like a code-completion popup. */
.popup {
position: absolute;
/* `@` / `/` completion; Popup keeps the list within the viewport. */
.caretMirror {
position: fixed;
top: 0;
left: 0;
bottom: calc(100% + 4px);
z-index: 10;
width: min(560px, 100%);
box-sizing: border-box;
visibility: hidden;
pointer-events: none;
white-space: pre-wrap;
overflow-wrap: break-word;
}
.popup {
width: min(560px, calc(100vw - 12px));
border-radius: var(--radius-popup);
cursor: default;
}
.items {
max-height: 300px;
overflow: auto;
padding: 4px 0;
border: 1px solid var(--border-popup);
border-radius: var(--radius-popup);
background: var(--bg-popup);
box-shadow: var(--shadow-popup);
cursor: default;
}
.item {
display: flex;
+49 -34
Переглянути файл
@@ -10,7 +10,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { notifications, OWNS_FILE_DROP } from "@/workbench/contributions";
import { Icon, IconButton, fileIconName } from "@/ui";
import { Icon, IconButton, Popup, fileIconName } from "@/ui";
import {
IMAGE_EXTENSIONS,
MAX_IMAGE_BYTES,
@@ -27,6 +27,7 @@ import {
type FileRef,
} from "./composerModel";
import { composerDraft, updateComposer, useAgents } from "./store";
import { useCompletionAnchor } from "./useCompletionAnchor";
import styles from "./Composer.module.css";
import { isImeKey } from "@/platform/ime";
@@ -127,13 +128,14 @@ export function Composer(props: ComposerProps) {
.map((command) => ({ kind: "command", command }));
}, [completion, files, props.commands]);
const open = !!completion && items.length > 0;
const completionAnchor = useCompletionAnchor(ref, open ? completion.to : null, text);
const setText = (value: string, caret?: number) => {
const setText = (value: string, caret?: number, restoreSelection = true) => {
updateComposer(id, { text: value });
const c = caret ?? value.length;
setCompletion(completionAt(value, c));
setActive(0);
if (caret !== undefined) {
if (caret !== undefined && restoreSelection) {
requestAnimationFrame(() => {
ref.current?.focus();
ref.current?.setSelectionRange(caret, caret);
@@ -281,36 +283,49 @@ export function Composer(props: ComposerProps) {
{...OWNS_FILE_DROP}
onClick={() => ref.current?.focus()}
>
{open && (
<div className={styles.popup} role="listbox" aria-label={tx(completion.kind === "file" ? "Files" : "Commands")}>
{items.map((item, i) => (
<div
key={item.kind === "file" ? item.path : item.command.name}
role="option"
aria-selected={i === active}
className={clsx(styles.item, i === active && styles.active)}
onMouseEnter={() => setActive(i)}
onMouseDown={(e) => {
e.preventDefault();
accept(item);
}}
>
{item.kind === "file" ? (
<>
<Icon name={fileIconName(basename(item.rel))} size={16} />
<span className={styles.itemName}>{basename(item.rel)}</span>
<span className={styles.itemDetail}>{item.rel}</span>
</>
) : (
<>
<span className={styles.itemName}>/{item.command.name}</span>
{item.command.hint && <span className={styles.itemHint}>{item.command.hint}</span>}
<span className={styles.itemDetail}>{item.command.description}</span>
</>
)}
</div>
))}
</div>
{open && completionAnchor && (
<Popup
open
anchor={completionAnchor}
placement="bottom-start"
autoFocus={false}
restoreFocus={false}
closeOnOutsideClick={false}
onClose={() => setCompletion(null)}
className={styles.popup}
role="listbox"
aria-label={tx(completion.kind === "file" ? "Files" : "Commands")}
>
<div className={styles.items}>
{items.map((item, i) => (
<div
key={item.kind === "file" ? item.path : item.command.name}
role="option"
aria-selected={i === active}
className={clsx(styles.item, i === active && styles.active)}
onMouseEnter={() => setActive(i)}
onMouseDown={(e) => {
e.preventDefault();
accept(item);
}}
>
{item.kind === "file" ? (
<>
<Icon name={fileIconName(basename(item.rel))} size={16} />
<span className={styles.itemName}>{basename(item.rel)}</span>
<span className={styles.itemDetail}>{item.rel}</span>
</>
) : (
<>
<span className={styles.itemName}>/{item.command.name}</span>
{item.command.hint && <span className={styles.itemHint}>{item.command.hint}</span>}
<span className={styles.itemDetail}>{item.command.description}</span>
</>
)}
</div>
))}
</div>
</Popup>
)}
{images.length > 0 && (
<div className={styles.images} onClick={(e) => e.stopPropagation()}>
@@ -339,7 +354,7 @@ export function Composer(props: ComposerProps) {
value={text}
aria-label={tx("Message")}
placeholder={tx(props.placeholder)}
onChange={(e) => setText(e.target.value, undefined)}
onChange={(e) => setText(e.target.value, e.target.selectionStart, false)}
onSelect={(e) => setCompletion(completionAt(e.currentTarget.value, e.currentTarget.selectionStart))}
onBlur={() => setCompletion(null)}
onKeyDown={onKeyDown}
+34
Переглянути файл
@@ -0,0 +1,34 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import type { AgentConfigOption } from "@/bindings";
import { ConfigPickers } from "./ConfigPickers";
it("shows Cursor approvals separately from its execution mode and sends the choice", () => {
const option = (id: string, category: string, values: string[]): AgentConfigOption => ({
id,
category,
name: category === "approval" ? "Approvals" : "Mode",
description: null,
via: "option",
current: values[0]!,
values: values.map((value) => ({
value,
name: value === "bypass" ? "Bypass approvals" : value,
description: null,
})),
});
const onChange = vi.fn();
render(
<ConfigPickers
config={[
option("mode", "mode", ["Agent", "Plan", "Ask"]),
option("openidea.cursor.approval", "approval", ["ask", "bypass"]),
]}
onChange={onChange}
/>,
);
expect(screen.getByText("Agent")).toBeVisible();
fireEvent.click(screen.getByLabelText("Approvals"));
fireEvent.click(screen.getByRole("option", { name: "Bypass approvals" }));
expect(onChange).toHaveBeenCalledWith("openidea.cursor.approval", "bypass");
});
+10 -3
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Model / mode / thinking-effort dropdowns for a composer's bottom row. Like other agent
* UIs, only the mode gets icons (one per mode, by what it allows); levels are plain text.
* Model, mode, approvals and thinking-effort dropdowns for a composer's bottom row.
* Modes and approvals use icons; levels are plain text.
*/
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
@@ -34,7 +34,14 @@ export function ConfigPickers({
options={o.values.map((v) => ({
value: v.value,
label: v.name,
icon: isMode ? modeIcon(v.value) : undefined,
icon:
o.category === "approval"
? v.value === "bypass"
? "unlock"
: "lock"
: isMode
? modeIcon(v.value)
: undefined,
detail: v.description ?? undefined,
}))}
onChange={(v) => onChange(o.id, v)}
+42
Переглянути файл
@@ -0,0 +1,42 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
import { Markdown } from "./Markdown";
const { openFile, openExternalUrl } = vi.hoisted(() => ({
openFile: vi.fn().mockResolvedValue(undefined),
openExternalUrl: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/workbench/contributions", () => ({ editorService: () => ({ openFile }) }));
vi.mock("@/platform/openUrl", () => ({ openExternalUrl }));
beforeEach(() => vi.clearAllMocks());
it.each([
["/Users/thomas/vmos-shots/tiktok-home.jpg", "/Users/thomas/vmos-shots/tiktok-home.jpg", undefined],
["images/home.jpg", "/repo/images/home.jpg", undefined],
["/tmp/截图%20one.jpg", "/tmp/截图 one.jpg", undefined],
["/repo/main.rs:12:5", "/repo/main.rs", { line: 11, col: 4 }],
["/repo/main.rs#L7", "/repo/main.rs", { line: 6, col: 0 }],
])("opens a Markdown file link: %s", (href, path, selection) => {
render(<Markdown text={`[查看文件](${href})`} cwd="/repo" />);
fireEvent.click(screen.getByRole("link", { name: "查看文件" }));
expect(openFile).toHaveBeenCalledWith(path, { focus: true, selection });
expect(openExternalUrl).not.toHaveBeenCalled();
});
it("keeps web links external", () => {
render(<Markdown text="[Website](https://example.com/image.jpg)" cwd="/repo" />);
fireEvent.click(screen.getByRole("link"));
expect(openExternalUrl).toHaveBeenCalledWith("https://example.com/image.jpg");
expect(openFile).not.toHaveBeenCalled();
});
it.each(["#section", "//example.com/image.jpg", "javascript:alert(1)", "/tmp/%ZZ.jpg"])(
"does not open unsupported links as files: %s",
(href) => {
const { container } = render(<Markdown text={`[Link](${href})`} cwd="/repo" />);
fireEvent.click(container.querySelector("a")!);
expect(openFile).not.toHaveBeenCalled();
expect(openExternalUrl).not.toHaveBeenCalled();
},
);
+7 -2
Переглянути файл
@@ -12,7 +12,7 @@ import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import { copyText } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { pathLink, type PathLink } from "./conversation";
import { fileHref, pathLink, type PathLink } from "./conversation";
import styles from "./Session.module.css";
const marked = new Marked({ gfm: true, breaks: true });
@@ -131,7 +131,12 @@ export function Markdown({ text, cwd }: { text: string; cwd: string }) {
const a = target.closest("a");
if (!a) return;
e.preventDefault();
if (/^https?:/i.test(a.href)) void openExternalUrl(a.href);
const href = a.getAttribute("href") ?? "";
if (/^https?:/i.test(href)) void openExternalUrl(href);
else {
const link = fileHref(href, cwd);
if (link) openPathLink(link);
}
}}
dangerouslySetInnerHTML={{ __html: html }}
/>
+2
Переглянути файл
@@ -126,6 +126,8 @@ describe("agent composer", () => {
const config = [option("fast", ["on"], null), option("mode", ["ask", "code"], "code"), option("model", ["m"], "m")];
expect(mainOptions(config).map((o) => o.id)).toEqual(["model", "mode"]);
expect(nextValue(config[1]!)).toBe("ask");
const approvals = { ...option("openidea.cursor.approval", ["ask", "bypass"], "ask"), category: "approval" };
expect(mainOptions([...config, approvals]).map((o) => o.id)).toEqual(["model", "mode", approvals.id]);
expect(
["default", "acceptEdits", "plan", "auto", "bypassPermissions", "auto_edit", "read-only", "x"].map(modeIcon),
).toEqual(["lock", "edit", "todo", "run", "unlock", "edit", "eye", "lock"]);
+18
Переглянути файл
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AgentCommand, AgentProvider } from "@/bindings";
const agentCommands = vi.fn();
@@ -86,4 +87,21 @@ describe("New Task composer commands", () => {
fireEvent.change(box, { target: { value: "/com" } });
expect(await screen.findByRole("option")).toHaveTextContent("/compact");
});
it("completes at the caret without replacing the rest of the message", async () => {
const user = userEvent.setup();
agentCommands.mockResolvedValue({ status: "ok", data: [command("compact", "Free up context")] });
render(<HomeEditor />);
await waitFor(() => expect(agentCommands).toHaveBeenCalled());
const box = screen.getByRole("textbox");
box.focus();
fireEvent.change(box, { target: { value: "/com keep this context", selectionStart: 4, selectionEnd: 4 } });
expect(await screen.findByRole("option")).toHaveTextContent("/compact");
expect(box).toHaveFocus();
await user.keyboard("{Tab}");
expect(box).toHaveValue("/compact keep this context");
await waitFor(() => expect(screen.queryByRole("listbox", { name: "Commands" })).toBeNull());
expect(agentCreate).not.toHaveBeenCalled();
});
});
+2 -2
Переглянути файл
@@ -109,9 +109,9 @@ export function atEdgeLine(text: string, caret: number, dir: -1 | 1): boolean {
return dir < 0 ? !text.slice(0, caret).includes("\n") : !text.slice(caret).includes("\n");
}
/** The settings shown as dropdowns: model, mode, thinking effort, in that order. */
/** The settings shown as dropdowns: model, mode, approvals, thinking effort, in that order. */
export function mainOptions(config: readonly AgentConfigOption[]): AgentConfigOption[] {
const order = ["model", "mode", "thought_level"];
const order = ["model", "mode", "approval", "thought_level"];
return order.flatMap((c) => config.filter((o) => o.category === c).slice(0, 1));
}
+19
Переглянути файл
@@ -22,6 +22,25 @@ export interface PathLink {
const PATH = /^(?:\.\/)?([\w.@-]+(?:\/[\w.@-]+)*\.[A-Za-z][A-Za-z0-9]*)(?::(\d+)(?::(\d+))?|#L(\d+))?$/;
/** Explicit Markdown links can also name files with spaces or non-ASCII names. */
export function fileHref(href: string, cwd: string): PathLink | null {
if (!href || href.startsWith("#") || href.startsWith("//") || /^[a-z][a-z\d+.-]*:/i.test(href)) return null;
let decoded: string;
try {
decoded = decodeURIComponent(href);
} catch {
return null;
}
const match = /^(.*?)(?::(\d+)(?::(\d+))?|#L(\d+))?$/.exec(decoded);
if (!match?.[1] || [...decoded].some((char) => char.charCodeAt(0) < 32)) return null;
const path = match[1].startsWith("/") ? match[1] : `${cwd.replace(/\/$/, "")}/${match[1]}`;
const link: PathLink = { path };
const line = match[2] ?? match[4];
if (line) link.line = Math.max(0, Number(line) - 1);
if (match[3]) link.col = Math.max(0, Number(match[3]) - 1);
return link;
}
/**
* The file an inline code span names (`src/lib.rs`, `src/main.rs:12`, `a/b.ts:3:5`,
* `/abs/x.py#L7`), resolved against `cwd`; null for text that isn't a file path
+69
Переглянути файл
@@ -0,0 +1,69 @@
import { useLayoutEffect, useState, type RefObject } from "react";
import type { VirtualElement } from "@floating-ui/react-dom";
import styles from "./Composer.module.css";
const TEXT_STYLES = [
"fontFamily",
"fontSize",
"fontWeight",
"fontStyle",
"fontVariant",
"lineHeight",
"letterSpacing",
"wordSpacing",
"textIndent",
"textAlign",
"textTransform",
"tabSize",
"paddingTop",
"paddingRight",
"paddingBottom",
"paddingLeft",
] as const;
/** A textarea has no text DOM to measure; mirror its wrapping and scroll offset. */
function caretRect(textarea: HTMLTextAreaElement, caret: number): DOMRect {
const computed = getComputedStyle(textarea);
const mirror = document.createElement("div");
mirror.className = styles.caretMirror ?? "";
for (const property of TEXT_STYLES) mirror.style[property] = computed[property];
mirror.style.width = `${textarea.clientWidth}px`;
mirror.textContent = textarea.value.slice(0, caret);
const marker = document.createElement("span");
marker.textContent = textarea.value.slice(caret) || "\u200b";
mirror.append(marker);
document.body.append(mirror);
try {
const box = textarea.getBoundingClientRect();
const lineHeight = parseFloat(computed.lineHeight) || parseFloat(computed.fontSize) * 1.5;
return new DOMRect(
box.left + textarea.clientLeft + marker.offsetLeft - textarea.scrollLeft,
box.top + textarea.clientTop + marker.offsetTop - textarea.scrollTop,
0,
lineHeight,
);
} finally {
mirror.remove();
}
}
export function useCompletionAnchor(
ref: RefObject<HTMLTextAreaElement | null>,
caret: number | null,
text: string,
): VirtualElement | null {
const [anchor, setAnchor] = useState<VirtualElement | null>(null);
useLayoutEffect(() => {
const textarea = ref.current;
if (!textarea || caret === null) {
setAnchor(null);
return;
}
const update = () =>
setAnchor({ contextElement: textarea, getBoundingClientRect: () => caretRect(textarea, caret) });
update();
textarea.addEventListener("scroll", update);
return () => textarea.removeEventListener("scroll", update);
}, [ref, caret, text]);
return anchor;
}
+2 -1
Переглянути файл
@@ -173,7 +173,8 @@
display: flex;
align-items: center;
gap: 6px;
overflow: hidden;
/* Let graph endpoints overlap adjacent rows; text is clipped by .subject. */
overflow: visible;
}
.colAuthor {
flex: none;
+8 -5
Переглянути файл
@@ -178,7 +178,7 @@ function LogView() {
.then((all) => {
if (!live) return;
const signature = JSON.stringify(all);
if (allRefs.current !== null && allRefs.current !== signature) void reloadLog();
if (allRefs.current !== null && allRefs.current !== signature) void reloadLog({ preserve: true });
allRefs.current = signature;
})
.catch(() => undefined);
@@ -215,7 +215,8 @@ function LogView() {
const refs = refsSignature(branch, branches) + JSON.stringify(useVcs.getState().heads);
const previous = lastRefs.current;
lastRefs.current = refs;
if (previous !== null && previous !== refs && useGitLog.getState().commits.length) void reloadLog();
if (previous !== null && previous !== refs && useGitLog.getState().commits.length)
void reloadLog({ preserve: true });
}, [version]);
return (
@@ -742,7 +743,7 @@ function FilterBar() {
onClear={() => setLogFilters({ path: null })}
/>
<span className={styles.grow} />
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog()} />
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog({ preserve: true })} />
<IconButton
icon="sort"
title="Graph Options"
@@ -1003,7 +1004,7 @@ function CommitList() {
const c = commits[v.index];
if (!c)
return (
<div key="loading" className={styles.row} style={{ transform: `translateY(${v.start}px)` }}>
<div key="loading" className={styles.row} style={{ top: v.start }}>
<Spinner size={12} />{" "}
<span className={styles.muted}>
<T>Loading…</T>
@@ -1075,7 +1076,7 @@ const CommitRow = memo(function CommitRow({
role="option"
aria-selected={selected}
className={clsx(styles.row, onBranch && styles.currentBranch, selected && styles.selected)}
style={{ transform: `translateY(${top}px)` }}
style={{ top }}
onMouseDown={(e) => {
if (e.shiftKey) e.preventDefault(); // no text selection on range clicks
onPick(commitKey(c), e);
@@ -1132,6 +1133,7 @@ export function GraphCell({ row, head }: { row: GraphRow; head?: boolean }) {
key={`u${i}`}
d={seg(x(s.from), 0, x(s.to), cy) + (s.arrow ? arrowHead(x(s.from), 0, -1) : "")}
stroke={laneColor(s.color)}
strokeLinecap={s.dashed ? "butt" : "square"}
strokeDasharray={s.dashed ? "2 2" : undefined}
/>
))}
@@ -1140,6 +1142,7 @@ export function GraphCell({ row, head }: { row: GraphRow; head?: boolean }) {
key={`d${i}`}
d={seg(x(s.from), cy, x(s.to), ROW) + (s.arrow ? arrowHead(x(s.to), ROW, 1) : "")}
stroke={laneColor(s.color)}
strokeLinecap={s.dashed ? "butt" : "square"}
strokeDasharray={s.dashed ? "2 2" : undefined}
/>
))}
+75
Переглянути файл
@@ -149,3 +149,78 @@ describe("multi-root Git log", () => {
}
});
});
describe("Git log background refresh", () => {
it("keeps history and selection visible until the replacement is ready", async () => {
useVcs.setState({ roots: ["/project/front"] });
log.mockResolvedValue({ status: "ok", data: [commit("old")] });
await reloadLog();
const before = useGitLog.getState();
selectCommit(commitKey(before.commits[0]!));
let finish!: (value: unknown) => void;
log.mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const refresh = reloadLog({ preserve: true });
await vi.waitFor(() => expect(finish).toBeDefined());
expect(useGitLog.getState().commits).toBe(before.commits);
expect(useGitLog.getState().rows).toBe(before.rows);
expect(useGitLog.getState().loading).toBe(true);
finish({ status: "ok", data: [commit("new"), commit("old")] });
await refresh;
expect(useGitLog.getState().commits.map((c) => c.id)).toEqual(["new", "old"]);
expect(useGitLog.getState().rows).toHaveLength(2);
expect(useGitLog.getState().selected).toBe(commitKey(before.commits[0]!));
expect(useGitLog.getState().loading).toBe(false);
});
it("refreshes the loaded range and resumes paging at the replacement's end", async () => {
useVcs.setState({ roots: ["/project/front"] });
const history = Array.from({ length: PAGE * 3 }, (_, i) => commit(String(i)));
log.mockImplementation(async (_repo, q) => ({ status: "ok", data: history.slice(q.skip, q.skip + q.limit) }));
await reloadLog();
await loadMore();
history.unshift(commit("new"));
await reloadLog({ preserve: true });
expect(useGitLog.getState().commits).toHaveLength(PAGE * 2);
expect(log.mock.lastCall?.[1]).toMatchObject({ skip: 0, limit: PAGE * 2 });
await loadMore();
expect(log.mock.lastCall?.[1]).toMatchObject({ skip: PAGE * 2, limit: PAGE });
expect(useGitLog.getState().commits.map((c) => c.id)).toEqual(history.slice(0, PAGE * 3).map((c) => c.id));
});
it("retains the current history if refreshing fails", async () => {
useVcs.setState({ roots: ["/project/front"] });
log.mockResolvedValue({ status: "ok", data: [commit("old")] });
await reloadLog();
const before = useGitLog.getState();
log.mockRejectedValue(new Error("unavailable"));
await reloadLog({ preserve: true });
expect(useGitLog.getState().commits).toBe(before.commits);
expect(useGitLog.getState().rows).toBe(before.rows);
expect(useGitLog.getState().error).toContain("unavailable");
expect(useGitLog.getState().loading).toBe(false);
});
it("ignores a refresh that finishes after the filters have changed", async () => {
useVcs.setState({ roots: ["/project/front"] });
let finish!: (value: unknown) => void;
log.mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const refresh = reloadLog({ preserve: true });
await vi.waitFor(() => expect(finish).toBeDefined());
useGitLog.setState({ filters: { ...emptyFilters(), text: "filtered" } });
log.mockResolvedValue({ status: "ok", data: [commit("filtered")] });
await reloadLog();
finish({ status: "ok", data: [commit("stale")] });
await refresh;
expect(useGitLog.getState().commits.map((c) => c.id)).toEqual(["filtered"]);
});
});
+25 -17
Переглянути файл
@@ -318,13 +318,11 @@ export function setLogFilters(patch: Partial<LogFilters>) {
void reloadLog();
}
/** Drops loaded commits and loads the first page. */
export function reloadLog(): Promise<void> {
/** Reloads history, optionally keeping the current view until its replacement arrives. */
export function reloadLog({ preserve = false }: { preserve?: boolean } = {}): Promise<void> {
useGitLog.setState((s) => ({
commits: [],
rows: [],
graph: emptyGraphState(),
done: false,
...(preserve ? {} : { commits: [], rows: [], graph: emptyGraphState(), done: false }),
loading: true,
error: null,
generation: s.generation + 1,
}));
@@ -334,7 +332,7 @@ export function reloadLog(): Promise<void> {
void currentUser().then((user) => {
if (useGitLog.getState().generation === generation) useGitLog.setState({ user });
});
return loadMore();
return loadPage(true);
}
async function loadOutgoing() {
@@ -376,16 +374,21 @@ export function isPushed(id: string): boolean {
}
export function loadMore(): Promise<void> {
return loadPage(false);
}
function loadPage(replace: boolean): Promise<void> {
const s = useGitLog.getState();
if (s.done) return Promise.resolve();
if (!replace && s.done) return Promise.resolve();
if (loadPromise) return loadPromise;
const gen = s.generation;
const f = s.filters;
// Settings › Version Control › Limit history to N rows (file / folder history).
const vcs = workflowSettings().vcs;
const cap = f.path && vcs.limitHistory ? vcs.historyLimit : Infinity;
if (s.commits.length >= cap) {
useGitLog.setState({ done: true });
const loaded = replace ? 0 : s.commits.length;
if (loaded >= cap) {
useGitLog.setState({ done: true, loading: false });
return Promise.resolve();
}
useGitLog.setState({ loading: true });
@@ -402,7 +405,7 @@ export function loadMore(): Promise<void> {
: useVcs.getState().roots.length
? useVcs.getState().roots
: [currentRepo()];
const limit = Math.min(PAGE, cap - s.commits.length);
const limit = Math.min(replace ? Math.max(PAGE, s.commits.length) : PAGE, cap - loaded);
const refs = await branchesByRepo(roots.filter((r): r is string => !!r));
const knownRefs = new Set(
Object.values(refs)
@@ -430,7 +433,7 @@ export function loadMore(): Promise<void> {
textRegex: f.regex,
textMatchCase: f.matchCase,
range: null,
skip: s.commits.filter((c) => commitRepo(c) === repo).length,
skip: replace ? 0 : s.commits.filter((c) => commitRepo(c) === repo).length,
limit,
order: o.sort,
firstParent: o.firstParent,
@@ -455,16 +458,21 @@ export function loadMore(): Promise<void> {
const page = mergeRepoLogs(streams, limit);
const cur = useGitLog.getState();
if (cur.generation !== gen) return;
const { rows, state } = computeGraph(page.map(graphCommit), cur.graph);
if (replace && failures.length === results.length && cur.commits.length) {
useGitLog.setState({ error: failures.join("\n") });
return;
}
const { rows, state } = computeGraph(page.map(graphCommit), replace ? emptyGraphState() : cur.graph);
useGitLog.setState({
commits: cur.commits.concat(page),
rows: cur.rows.concat(rows),
commits: replace ? page : cur.commits.concat(page),
rows: replace ? rows : cur.rows.concat(rows),
graph: state,
done: page.length < PAGE || cur.commits.length + page.length >= cap,
done: page.length < limit || loaded + page.length >= cap,
error: failures.join("\n") || null,
});
} catch (e) {
if (useGitLog.getState().generation === gen) useGitLog.setState({ error: errorMessage(e), done: true });
if (useGitLog.getState().generation === gen)
useGitLog.setState({ error: errorMessage(e), done: replace && s.commits.length ? s.done : true });
} finally {
if (useGitLog.getState().generation === gen) {
useGitLog.setState({ loading: false });