дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 04:56:08 +02:00
Порівняти коміти
4
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
cd89f57c5f | ||
|
|
0cc873565a | ||
|
|
7cc100367d | ||
|
|
39c0f6676e |
No files matched your search
@@ -2,8 +2,8 @@
|
||||
//! the agent reports them over ACP.
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentUsage,
|
||||
AgentCommand, AgentCommandSource, AgentConfigChoice, AgentConfigOption, AgentConfigValue, AgentConfigVia,
|
||||
AgentCost, AgentLimit, AgentModelPricing, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -54,6 +54,30 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Whether `value` of `option` approves everything without asking.
|
||||
pub(crate) fn approves_everything(option: &AgentConfigOption, value: &str) -> bool {
|
||||
option.category.as_deref().and_then(bypass_value).is_some_and(|bypass| bypass(value))
|
||||
}
|
||||
|
||||
/// The choices that keep a session asking before it changes anything: `wanted` without values
|
||||
/// that approve everything, and an asking value for each option of `options` that approves
|
||||
/// everything as it stands.
|
||||
pub(crate) fn asking_choices(options: &[AgentConfigOption], wanted: &[AgentConfigChoice]) -> Vec<AgentConfigChoice> {
|
||||
let mut out: Vec<AgentConfigChoice> = wanted
|
||||
.iter()
|
||||
.filter(|c| !options.iter().any(|o| o.id == c.id && approves_everything(o, &c.value)))
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut asking = options.to_vec();
|
||||
ask_for_approvals(&mut asking);
|
||||
for (before, after) in options.iter().zip(&asking) {
|
||||
let Some(value) = after.current.as_ref().filter(|v| before.current.as_ref() != Some(*v)) else { continue };
|
||||
out.retain(|c| c.id != after.id);
|
||||
out.push(AgentConfigChoice { id: after.id.clone(), value: value.clone() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
@@ -464,6 +488,22 @@ mod tests {
|
||||
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asking_choices_drop_and_override_values_that_approve_everything() {
|
||||
let codex = options_of(&json!({"modes": {"currentModeId": "full-access",
|
||||
"availableModes": [{"id": "read-only"}, {"id": "ask"}, {"id": "auto"}, {"id": "full-access"}]}}));
|
||||
let mode = codex[0].id.clone();
|
||||
let choice = |id: &str, value: &str| AgentConfigChoice { id: id.into(), value: value.into() };
|
||||
// The source task's Full Access goes; the session's own Full Access is turned to Ask.
|
||||
let wanted = asking_choices(&codex, &[choice(&mode, "full-access"), choice("model", "gpt")]);
|
||||
assert_eq!(wanted, [choice("model", "gpt"), choice(&mode, "ask")]);
|
||||
// A mode that already asks is left alone.
|
||||
let mut auto = codex.clone();
|
||||
auto[0].current = Some("auto".into());
|
||||
assert_eq!(asking_choices(&auto, &[choice(&mode, "auto")]), [choice(&mode, "auto")]);
|
||||
assert!(approves_everything(&codex[0], "full-access") && !approves_everything(&codex[0], "auto"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
let mut c = options_of(&json!({
|
||||
|
||||
@@ -891,6 +891,8 @@ impl AgentManager {
|
||||
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the topic first"))?;
|
||||
let title = title_of(&prompt);
|
||||
let mut config = self.merged_config(&spec.id, &req.config);
|
||||
// The source task's choices may approve everything; the side conversation asks.
|
||||
let wanted = config::asking_choices(&config, &req.config);
|
||||
config::ask_for_approvals(&mut config);
|
||||
if config::bypass_approvals(&config) {
|
||||
return Err(IdeError::invalid(
|
||||
@@ -933,7 +935,7 @@ impl AgentManager {
|
||||
task: task.clone(),
|
||||
session_id: None,
|
||||
entries: Vec::new(),
|
||||
wanted: req.config,
|
||||
wanted,
|
||||
before,
|
||||
saved: None,
|
||||
touched: None,
|
||||
@@ -1050,6 +1052,9 @@ impl AgentManager {
|
||||
if !o.values.iter().any(|v| v.value == value) {
|
||||
return Err(IdeError::invalid(format!("{} has no value {value}", o.name)));
|
||||
}
|
||||
if s.ephemeral && config::approves_everything(o, &value) {
|
||||
return Err(IdeError::invalid("a side conversation asks before changing anything"));
|
||||
}
|
||||
o.clone()
|
||||
};
|
||||
let previous = target.current.clone();
|
||||
@@ -2365,7 +2370,10 @@ impl Task {
|
||||
}
|
||||
let (mut options, mut wanted) = {
|
||||
let s = self.state.lock();
|
||||
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
|
||||
let options = if known { reported } else { s.task.config.clone() };
|
||||
// A side conversation asks before anything, whatever mode the agent starts in.
|
||||
let wanted = if s.ephemeral { config::asking_choices(&options, &s.wanted) } else { s.wanted.clone() };
|
||||
(options, wanted)
|
||||
};
|
||||
config::add_client_options(provider_id, &mut options);
|
||||
// Changing model can replace the effort / context-tier choices; validate those only afterwards.
|
||||
|
||||
@@ -167,7 +167,10 @@ The `url` field in the result is as written in the file (unsubstituted); transpo
|
||||
}
|
||||
call.confirm(&subject, Some(detail)).await?;
|
||||
|
||||
let exchange = ide_http::run(input, &call.cancel).await?;
|
||||
// Exactly the request the user approved: preparing it again would read the
|
||||
// environment files again, which may name another destination by now.
|
||||
let redact_url = prepared.url.clone();
|
||||
let exchange = ide_http::send(prepared, Some(&path), &call.cancel).await?;
|
||||
let history = call.project().http_history.clone();
|
||||
let saved = exchange.clone();
|
||||
let _ = call.host().blocking(move || history.add(&saved)).await;
|
||||
@@ -188,7 +191,7 @@ The `url` field in the result is as written in the file (unsubstituted); transpo
|
||||
"status": response.map(|r| r.status),
|
||||
"statusText": response.map(|r| r.status_text.clone()),
|
||||
"totalMs": response.map(|r| r.total_ms).or(exchange.entry.total_ms),
|
||||
"error": redact_transport_error(exchange.entry.error.clone(), &prepared.url),
|
||||
"error": redact_transport_error(exchange.entry.error.clone(), &redact_url),
|
||||
"body": body,
|
||||
"bodyTruncated": body_truncated,
|
||||
}))
|
||||
|
||||
@@ -34,6 +34,16 @@ pub struct RunInput<'a> {
|
||||
/// variables, missing includes) fail; transport errors are part of the exchange.
|
||||
pub async fn run(input: RunInput<'_>, cancel: &CancellationToken) -> IdeResult<HttpExchange> {
|
||||
let request = prepare(&input)?;
|
||||
send(request, input.file, cancel).await
|
||||
}
|
||||
|
||||
/// Sends an already prepared request (one the user approved as shown); `file` is the
|
||||
/// request file it came from, for the history.
|
||||
pub async fn send(
|
||||
request: PreparedRequest,
|
||||
file: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<HttpExchange> {
|
||||
let time_ms = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs_f64() * 1000.0)
|
||||
@@ -57,7 +67,7 @@ pub async fn run(input: RunInput<'_>, cancel: &CancellationToken) -> IdeResult<H
|
||||
url: request.url.clone(),
|
||||
status: response.as_ref().map(|r| r.status),
|
||||
total_ms: response.as_ref().map(|r| r.total_ms),
|
||||
file: input.file.map(IpcPath::from),
|
||||
file: file.map(IpcPath::from),
|
||||
error,
|
||||
},
|
||||
request,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { MethodSignature } from "@/bindings";
|
||||
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -46,7 +46,11 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
const ready = !busy && !problem && signatureChanged(info, signature);
|
||||
const current = Math.min(selected, rows.length - 1);
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => running.current?.abort(), []);
|
||||
const close = () => {
|
||||
running.current?.abort();
|
||||
useSignatureDialog.setState({ request: null });
|
||||
request.view.focus();
|
||||
};
|
||||
@@ -72,9 +76,10 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
};
|
||||
const submit = async (preview: boolean) => {
|
||||
if (!ready) return;
|
||||
const run = (running.current = new AbortController());
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const outcome = await changeSignature(request, signature, delegate, preview);
|
||||
const outcome = await changeSignature(request, signature, delegate, preview, run.signal);
|
||||
if (useSignatureDialog.getState().request !== request) return;
|
||||
setBusy(false);
|
||||
if (outcome.status === "done") close();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** IDEA's Extract Interface dialog for Java classes (`extractInterface.ts`). */
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import {
|
||||
@@ -39,7 +39,11 @@ function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest })
|
||||
const ready = !busy && !problem && !!target;
|
||||
const allChecked = checked.size === info.members.length;
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => running.current?.abort(), []);
|
||||
const close = () => {
|
||||
running.current?.abort();
|
||||
useExtractInterfaceDialog.setState({ request: null });
|
||||
request.view.focus();
|
||||
};
|
||||
@@ -52,10 +56,11 @@ function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest })
|
||||
});
|
||||
const submit = async (preview: boolean) => {
|
||||
if (!ready) return;
|
||||
const run = (running.current = new AbortController());
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const members = info.members.map((m) => m.handleIdentifier).filter((id) => checked.has(id));
|
||||
const outcome = await extractInterface(request, trimmed, target, members, preview);
|
||||
const outcome = await extractInterface(request, trimmed, target, members, preview, run.signal);
|
||||
if (useExtractInterfaceDialog.getState().request !== request) return;
|
||||
setBusy(false);
|
||||
if (outcome.status === "done") close();
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const cancelRequest = vi.fn(async (_id: number) => ({ status: "ok", data: null }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const ipc = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...ipc, commands: { ...ipc.commands, cancelRequest } };
|
||||
});
|
||||
|
||||
const { cancellable } = await import("./signature");
|
||||
|
||||
describe("cancellable refactoring requests", () => {
|
||||
it("cancels the request in flight when the dialog closes", async () => {
|
||||
const run = new AbortController();
|
||||
let sent = -1;
|
||||
let answer!: (v: string) => void;
|
||||
const reply = cancellable(run.signal, (id) => {
|
||||
sent = id;
|
||||
return new Promise<string>((r) => (answer = r));
|
||||
});
|
||||
run.abort();
|
||||
expect(cancelRequest).toHaveBeenCalledWith(sent);
|
||||
answer("late");
|
||||
await expect(reply).resolves.toBe("late");
|
||||
});
|
||||
|
||||
it("leaves a request alone once it answered", async () => {
|
||||
cancelRequest.mockClear();
|
||||
const run = new AbortController();
|
||||
await cancellable(run.signal, async () => "done");
|
||||
run.abort();
|
||||
expect(cancelRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -25,5 +25,9 @@ describe("extract interface", () => {
|
||||
expect(interfaceProblem("Shape", "Shape", 1)).toBe("Interface name should differ from the class name");
|
||||
expect(interfaceProblem("HasArea", "Shape", 0)).toBe("Select the members to form the interface");
|
||||
expect(interfaceProblem("HasArea", "Shape", 2)).toBeNull();
|
||||
// Java identifiers take letters of any script.
|
||||
expect(interfaceProblem("处理器", "Shape", 1)).toBeNull();
|
||||
expect(interfaceProblem("Größe", "Shape", 1)).toBeNull();
|
||||
expect(interfaceProblem("a-b", "Shape", 1)).toBe("Interface name is not a valid identifier");
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@ import { tx } from "@/platform/i18n";
|
||||
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { cannotPerform } from "./catalog";
|
||||
import { applyEdit, confirmProblems } from "./signature";
|
||||
import { JAVA_NAME, applyEdit, cancellable, confirmProblems } from "./signature";
|
||||
|
||||
/** Languages whose server extracts interfaces through the dialog. */
|
||||
export const EXTRACT_INTERFACE_LANGUAGES = new Set(["java"]);
|
||||
@@ -51,8 +51,6 @@ export function memberLabel(m: InterfaceMember): string {
|
||||
return `${m.name}${params}: ${m.typeName}`;
|
||||
}
|
||||
|
||||
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
|
||||
|
||||
/** Why the interface can't be extracted yet, or null. */
|
||||
export function interfaceProblem(name: string, className: string, members: number): string | null {
|
||||
if (!name) return "No interface name specified";
|
||||
@@ -127,6 +125,8 @@ export async function extractInterface(
|
||||
pkg: PackageChoice,
|
||||
members: readonly string[],
|
||||
preview: boolean,
|
||||
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
|
||||
signal?: AbortSignal,
|
||||
): Promise<InterfaceOutcome> {
|
||||
const { view } = request;
|
||||
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
|
||||
@@ -136,18 +136,22 @@ export async function extractInterface(
|
||||
for (;;) {
|
||||
await whenSynced(view);
|
||||
const token: string | null = confirmation;
|
||||
extracted = await lspRequest(() =>
|
||||
commands.lspExtractInterface(nextRequestId(), request.doc, request.pos, [...members], name, pkg.json, token),
|
||||
extracted = await cancellable(signal, (id) =>
|
||||
lspRequest(() =>
|
||||
commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
|
||||
),
|
||||
);
|
||||
if (signal?.aborted) return { status: "stay" };
|
||||
const fatal = extracted.problems.find((p) => p.severity === "fatal");
|
||||
if (fatal || (!extracted.edit && !extracted.confirmation))
|
||||
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
|
||||
if (!extracted.confirmation) break;
|
||||
if (!(await confirmProblems(extracted.problems.map((p) => p.message)))) return { status: "stay" };
|
||||
if (!(await confirmProblems(extracted.problems.map((p) => p.message))) || signal?.aborted)
|
||||
return { status: "stay" };
|
||||
confirmation = extracted.confirmation;
|
||||
}
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return { status: "stay" };
|
||||
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
|
||||
return { status: "stay", error: errorText(e) };
|
||||
}
|
||||
const edit = extracted.edit!;
|
||||
|
||||
@@ -23,6 +23,10 @@ describe("change signature", () => {
|
||||
it("tells what keeps the signature from being submitted", () => {
|
||||
expect(signatureProblem(info)).toBeNull();
|
||||
expect(signatureProblem({ ...info, methodName: "2x" })).toBe("Method name is not a valid identifier");
|
||||
expect(signatureProblem({ ...info, methodName: "处理" })).toBeNull();
|
||||
expect(
|
||||
signatureProblem({ ...info, parameters: info.parameters.map((p, i) => ({ ...p, name: `数量${i}` })) }),
|
||||
).toBeNull();
|
||||
expect(signatureProblem({ ...info, returnType: " " })).toBe("Return type is not specified");
|
||||
const dup = { ...info, parameters: [info.parameters[0]!, { ...info.parameters[1]!, name: "a" }] };
|
||||
expect(signatureProblem(dup)).toBe("Duplicate parameter name");
|
||||
|
||||
@@ -50,7 +50,8 @@ export function signatureText(sig: {
|
||||
return head + throws;
|
||||
}
|
||||
|
||||
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
|
||||
/** A Java identifier: letters of any script, `$` and `_`, then digits and combining marks too. */
|
||||
export const JAVA_NAME = /^[\p{L}\p{Nl}\p{Sc}\p{Pc}][\p{L}\p{Nl}\p{Sc}\p{Pc}\p{Nd}\p{Mn}\p{Mc}]*$/u;
|
||||
|
||||
/** Why the edited signature can't be submitted yet, or null. */
|
||||
export function signatureProblem(sig: MethodSignature): string | null {
|
||||
@@ -137,6 +138,18 @@ export async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends `send(id)` with a fresh request id that `signal` cancels. */
|
||||
export async function cancellable<T>(signal: AbortSignal | undefined, send: (id: number) => Promise<T>): Promise<T> {
|
||||
const id = nextRequestId();
|
||||
const abort = () => void commands.cancelRequest(id);
|
||||
signal?.addEventListener("abort", abort);
|
||||
try {
|
||||
return await send(id);
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmProblems(messages: readonly string[]): Promise<boolean> {
|
||||
const { button } = await ask({
|
||||
title: "Problems Detected",
|
||||
@@ -158,6 +171,8 @@ export async function changeSignature(
|
||||
signature: MethodSignature,
|
||||
delegate: boolean,
|
||||
preview: boolean,
|
||||
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
|
||||
signal?: AbortSignal,
|
||||
): Promise<SignatureOutcome> {
|
||||
const { view } = request;
|
||||
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
|
||||
@@ -167,18 +182,20 @@ export async function changeSignature(
|
||||
for (;;) {
|
||||
await whenSynced(view);
|
||||
const token: string | null = confirmation;
|
||||
changed = await lspRequest(() =>
|
||||
commands.lspChangeSignature(nextRequestId(), request.doc, request.pos, signature, delegate, token),
|
||||
changed = await cancellable(signal, (id) =>
|
||||
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token)),
|
||||
);
|
||||
if (signal?.aborted) return { status: "stay" };
|
||||
const fatal = changed.problems.find((p) => p.severity === "fatal");
|
||||
if (fatal || (!changed.edit && !changed.confirmation))
|
||||
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
|
||||
if (!changed.confirmation) break;
|
||||
if (!(await confirmProblems(changed.problems.map((p) => p.message)))) return { status: "stay" };
|
||||
if (!(await confirmProblems(changed.problems.map((p) => p.message))) || signal?.aborted)
|
||||
return { status: "stay" };
|
||||
confirmation = changed.confirmation;
|
||||
}
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return { status: "stay" };
|
||||
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
|
||||
return { status: "stay", error: errorText(e) };
|
||||
}
|
||||
const edit = changed.edit!;
|
||||
|
||||
@@ -281,3 +281,32 @@ it("confirmLeave asks about running processes before closing", async () => {
|
||||
expect(asked[0]?.title).toContain("app");
|
||||
expect(asked[0]?.body).toContain("app");
|
||||
});
|
||||
|
||||
it("counts untitled buffers only when leaving for Welcome, and stays when one isn't saved", async () => {
|
||||
const service = await import("@/workbench/contributions");
|
||||
const { confirmLeave } = await import("../closeGuard");
|
||||
let untitled = [7];
|
||||
const spy = vi.spyOn(service, "maybeEditorService").mockReturnValue({
|
||||
dirtyDocumentIds: () => [7],
|
||||
untitledDirtyDocumentIds: () => untitled,
|
||||
saveAll: vi.fn(async () => {}),
|
||||
} as never);
|
||||
try {
|
||||
// Another project in place keeps the buffer: nothing to ask.
|
||||
const kept = deps([]);
|
||||
await expect(confirmLeave(kept.d, "openidea", true)).resolves.toBe(true);
|
||||
expect(kept.asked).toHaveLength(0);
|
||||
// Close Project asks; Save with the Save As cancelled keeps the project open, quietly.
|
||||
const left = deps([{ button: "save", checked: false }]);
|
||||
await expect(confirmLeave(left.d, "openidea", false)).resolves.toBe(false);
|
||||
expect(left.asked[0]?.body).toContain("1");
|
||||
expect(left.d.saveAll).toHaveBeenCalled();
|
||||
// Saved: the project closes.
|
||||
untitled = [];
|
||||
const saved = deps([{ button: "save", checked: false }]);
|
||||
left.d.saveAll = vi.fn(async () => {});
|
||||
await expect(confirmLeave(saved.d, "openidea", false)).resolves.toBe(true);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
@@ -12,7 +12,7 @@
|
||||
* `general.closeWithoutWelcome` is on, in which case it closes. When
|
||||
* `general.closeTabsWithWindow` is on, that close drops the saved editor tabs.
|
||||
*/
|
||||
import { commands, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { closeProject, provideLeaveProjectGuard, useProject } from "@/platform/project";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
@@ -171,6 +171,7 @@ const defaultDeps: CloseDeps = {
|
||||
while ((await liveProcesses()).length > 0) await new Promise((r) => setTimeout(r, 100));
|
||||
},
|
||||
onSaveFailed: (e) =>
|
||||
!isCancelled(e) &&
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.unsaved.saveFailed"),
|
||||
@@ -224,7 +225,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
const s = useProject.getState();
|
||||
// The last project or LightEdit window can return to Welcome. Otherwise it closes.
|
||||
if (returnsToWelcome(ctx.quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings)) {
|
||||
if (await confirmLeave(deps)) {
|
||||
if (await confirmLeave(deps, undefined, false)) {
|
||||
forgot = forgetTabs();
|
||||
try {
|
||||
await closeProject();
|
||||
@@ -276,16 +277,27 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
export async function confirmLeave(
|
||||
deps: CloseDeps = defaultDeps,
|
||||
project = (useProject.getState().project?.displayName || useProject.getState().project?.name) ?? null,
|
||||
keepUntitled = true,
|
||||
): Promise<boolean> {
|
||||
if (!(await closeDocumentWindows())) return false;
|
||||
const confirmTerminate = workflowSettings().run.confirmTerminate;
|
||||
// Untitled buffers follow the window across projects: they are neither
|
||||
// counted nor saved by this guard (the window keeps them open).
|
||||
const untitled = new Set(maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []);
|
||||
// Untitled buffers follow the window into another project: they are neither counted nor
|
||||
// saved then (the window keeps them open). Closing to Welcome drops them, so they count.
|
||||
const untitled = new Set(keepUntitled ? (maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []) : []);
|
||||
const saveDeps: CloseDeps =
|
||||
untitled.size > 0
|
||||
? { ...deps, saveAll: () => Promise.resolve(maybeEditorService()?.saveAll({ skipUntitled: true })) }
|
||||
: deps;
|
||||
: keepUntitled
|
||||
? deps
|
||||
: {
|
||||
...deps,
|
||||
// Save asks for each untitled buffer's path; one left unsaved (Save As cancelled) keeps the project open.
|
||||
saveAll: async () => {
|
||||
await deps.saveAll();
|
||||
if (maybeEditorService()?.untitledDirtyDocumentIds?.().length)
|
||||
throw new IpcError({ kind: "cancelled", message: "Untitled files were not saved" });
|
||||
},
|
||||
};
|
||||
return decideClose(
|
||||
{
|
||||
quitting: false,
|
||||
@@ -331,7 +343,7 @@ export function installCloseGuard(deps: CloseDeps = defaultDeps): () => void {
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root || s.lightEdit !== prev.lightEdit) dirtyDocs.clear();
|
||||
}),
|
||||
provideLeaveProjectGuard(() => confirmLeave(deps)),
|
||||
provideLeaveProjectGuard((keepUntitled) => confirmLeave(deps, undefined, keepUntitled)),
|
||||
];
|
||||
let unlisten: (() => void) | undefined;
|
||||
let disposed = false;
|
||||
|
||||
@@ -79,7 +79,7 @@ export function activate(): () => void {
|
||||
keywords: ["ssh", "remote", "close"],
|
||||
when: "projectOpen",
|
||||
run: async () => {
|
||||
if (!(await confirmLeaveProject())) return;
|
||||
if (!(await confirmLeaveProject(false))) return;
|
||||
try {
|
||||
await disconnectRemote();
|
||||
} catch (e) {
|
||||
|
||||
@@ -2157,5 +2157,6 @@
|
||||
"Extract Interface from '{name}'": "Extract Interface from '{name}'",
|
||||
"The interface could not be extracted": "The interface could not be extracted",
|
||||
"Extract Interface is not supported for {name}": "Extract Interface is not supported for {name}",
|
||||
"Package for new interface": "Package for new interface"
|
||||
"Package for new interface": "Package for new interface",
|
||||
"Untitled files were not saved": "Untitled files were not saved"
|
||||
}
|
||||
@@ -8540,5 +8540,6 @@
|
||||
"Extract Interface from '{name}'": "从 '{name}' 提取接口",
|
||||
"The interface could not be extracted": "无法提取接口",
|
||||
"Extract Interface is not supported for {name}": "{name} 不支持提取接口",
|
||||
"Package for new interface": "新接口的软件包"
|
||||
"Package for new interface": "新接口的软件包",
|
||||
"Untitled files were not saved": "未命名文件未保存"
|
||||
}
|
||||
@@ -25,20 +25,26 @@ export const useProject = create<ProjectState>(() => ({
|
||||
|
||||
useProject.subscribe((s) => setContext("projectOpening", s.openingPath !== null));
|
||||
|
||||
let leaveGuard: (() => Promise<boolean>) | null = null;
|
||||
/** `keepUntitled`: the window opens another project in place and keeps its untitled buffers. */
|
||||
type LeaveGuard = (keepUntitled: boolean) => Promise<boolean>;
|
||||
let leaveGuard: LeaveGuard | null = null;
|
||||
|
||||
/** Installs the check run before this window leaves its project (unsaved changes). */
|
||||
export function provideLeaveProjectGuard(guard: () => Promise<boolean>): () => void {
|
||||
export function provideLeaveProjectGuard(guard: LeaveGuard): () => void {
|
||||
leaveGuard = guard;
|
||||
return () => {
|
||||
if (leaveGuard === guard) leaveGuard = null;
|
||||
};
|
||||
}
|
||||
|
||||
/** False when the user chose to stay (another project in place, Close Project). */
|
||||
export function confirmLeaveProject(): Promise<boolean> {
|
||||
/**
|
||||
* False when the user chose to stay (another project in place, Close Project). Untitled buffers
|
||||
* follow the window only into another local project (`keepUntitled`); leaving for Welcome or a
|
||||
* remote host asks about them too.
|
||||
*/
|
||||
export function confirmLeaveProject(keepUntitled = true): Promise<boolean> {
|
||||
const s = useProject.getState();
|
||||
return (s.project || s.lightEdit) && leaveGuard ? leaveGuard() : Promise.resolve(true);
|
||||
return (s.project || s.lightEdit) && leaveGuard ? leaveGuard(keepUntitled) : Promise.resolve(true);
|
||||
}
|
||||
|
||||
let startupLaunch: Promise<void> | null = null;
|
||||
|
||||
@@ -65,7 +65,8 @@ export async function openRemoteProject(
|
||||
await call(commands.windowOpenRemote(target, path, true));
|
||||
return true;
|
||||
}
|
||||
if (!(await confirmLeaveProject())) return false;
|
||||
// The remote host's project doesn't take this window's untitled buffers.
|
||||
if (!(await confirmLeaveProject(false))) return false;
|
||||
try {
|
||||
await here();
|
||||
return true;
|
||||
|
||||
@@ -69,7 +69,7 @@ export function registerShellActions(): () => void {
|
||||
category: "File",
|
||||
when: "projectOpen",
|
||||
run: async () => {
|
||||
if (!useProject.getState().project || !(await confirmLeaveProject())) return;
|
||||
if (!useProject.getState().project || !(await confirmLeaveProject(false))) return;
|
||||
try {
|
||||
await closeProject();
|
||||
} catch (e) {
|
||||
|
||||
Reference in new issue
Заблокувати користувача