The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
feat(app): close the last window instead of returning to Welcome (#2321)
LzSkylinec1a6079ee173
diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rsindex 5a9cbd612..de8b16b3c 100644--- a/crates/ide-core/src/settings.rs+++ b/crates/ide-core/src/settings.rs@@ -277,6 +277,10 @@ pub struct CustomKeymap {pub struct GeneralSettings {pub reopen_last_project: bool,pub confirm_exit: bool,+ /// When on, the last window closes instead of showing the Welcome screen.+ pub close_without_welcome: bool,+ /// When on, closing a window drops its saved editor tabs, so they are not restored next time.+ pub close_tabs_with_window: bool,/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.pub open_project_in: String,/// Initial folder of the Open / Clone dialogs; empty = the OS default.@@ -300,6 +304,8 @@ impl Default for GeneralSettings {Self {reopen_last_project: true,confirm_exit: true,+ close_without_welcome: false,+ close_tabs_with_window: false,open_project_in: "ask".into(),default_project_directory: String::new(),save_on_idle: false,@@ -1196,6 +1202,26 @@ impl Settings {mod tests {use super::*;+ #[test]+ fn window_close_settings_default_off_and_round_trip() {+ for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {+ let settings: Settings = serde_json::from_str(old).unwrap();+ assert!(!settings.general.close_without_welcome);+ assert!(!settings.general.close_tabs_with_window);+ }+ for close_window in [false, true] {+ for close_tabs in [false, true] {+ let mut settings = Settings::default();+ settings.general.close_without_welcome = close_window;+ settings.general.close_tabs_with_window = close_tabs;+ let json = serde_json::to_value(&settings).unwrap();+ assert_eq!(json["general"]["closeWithoutWelcome"], close_window);+ assert_eq!(json["general"]["closeTabsWithWindow"], close_tabs);+ assert_eq!(serde_json::from_value::<Settings>(json).unwrap().general, settings.general);+ }+ }+ }+#[test]fn cmake_profile_argument_arrays_round_trip() {let mut settings = Settings::default();diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rsindex d8f1dbf4c..9645f4787 100644--- a/src-tauri/src/commands/window.rs+++ b/src-tauri/src/commands/window.rs@@ -225,7 +225,7 @@ pub fn window_close_context(app: AppHandle, window: Window, windows: State<'_, Wwindows.pending_closes().iter().map(String::as_str).filter(|l| all.iter().any(|a| a == l)),);// Members of a tab group asking to close together are one window closing: the first of them- // is the last window left (it returns to the welcome screen); the others just close.+ // is the last window left (the frontend may return it to the welcome screen); the others just close.let count = match pending.first() {Some(keeper) if pending.len() > 1 && keeper == window.label() => all.len() - pending.len() + 1,_ => all.len(),diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex d9215f4a7..054858836 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -258,6 +258,11 @@ pub fn run() {window_groups::destroyed(window.app_handle(), window.label());windows::close_auxiliary_windows(window.app_handle(), window.label());if let Some(state) = window.try_state::<AppState>() {+ #[cfg(target_os = "macos")]+ if let Some(w) = window.try_state::<WindowsState>() {+ let settings = ide_host::ops::project::settings(&state.host, window.label());+ w.keep_alive.store(settings.general.close_without_welcome, std::sync::atomic::Ordering::SeqCst);+ }state.updates.forget_window(window.label());state.close_project(window.label());state.plugins.forget_client(window.label());@@ -275,6 +280,21 @@ pub fn run() {.build(context).expect("error while running OpenIDEA").run(move |app, event| {+ #[cfg(target_os = "macos")]+ match &event {+ tauri::RunEvent::ExitRequested { code: None, api, .. }+ if app.state::<WindowsState>().keep_alive.load(std::sync::atomic::Ordering::SeqCst)+ && !app.state::<WindowsState>().quitting() =>+ {+ api.prevent_exit();+ }+ tauri::RunEvent::Reopen { has_visible_windows: false, .. }+ if windows::project_window_labels(app).is_empty() =>+ {+ windows::spawn_window(app, None);+ }+ _ => {}+ }#[cfg(target_os = "macos")]if let tauri::RunEvent::Opened { urls } = &event {let paths = windows::opened_paths(urls);diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rsindex 601f0cb2a..4841077fd 100644--- a/src-tauri/src/windows.rs+++ b/src-tauri/src/windows.rs@@ -159,6 +159,9 @@ pub struct WindowsState {last_focused: Mutex<Option<String>>,/// Set by Quit while windows close one by one.quitting: AtomicBool,+ /// The last closed project opted out of Welcome; macOS keeps its app in the Dock.+ #[cfg(target_os = "macos")]+ pub keep_alive: AtomicBool,/// Windows asked to close whose guards have not finished. AppKit closes a whole tab group at/// once, so its members ask together.close_requests: Mutex<Vec<String>>,diff --git a/src/bindings.ts b/src/bindings.tsindex 78d0a23e4..456e76a7f 100644--- a/src/bindings.ts+++ b/src/bindings.ts@@ -4388,6 +4388,10 @@ export type FunctionBreakpoint = {export type GeneralSettings = {reopenLastProject?: boolean,confirmExit?: boolean,+ /** When on, the last window closes instead of showing the Welcome screen. */+ closeWithoutWelcome?: boolean,+ /** When on, closing a window drops its saved editor tabs, so they are not restored next time. */+ closeTabsWithWindow?: boolean,/** Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`. */openProjectIn?: string,/** Initial folder of the Open / Clone dialogs; empty = the OS default. */diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.tsindex f103e11e7..97843b8f5 100644--- a/src/editor/core/controller.ts+++ b/src/editor/core/controller.ts@@ -221,6 +221,8 @@ export class EditorController implements SlotHost {private disposers: Array<() => void> = [];/** Project root (or {@link LIGHT_EDIT_SESSION}) whose editor session is being tracked (null while switching). */private sessionRoot: string | null = null;+ /** Session keys a window close dropped. Restoring one starts empty, and saves stay empty until then. */+ private forgottenSessions = new Set<string>();private sessionTimer: ReturnType<typeof setTimeout> | undefined;/** Restored caret / scroll per path, applied when the file's first slot is created. */private restoredViews = new Map<string, FileViewState>();@@ -495,6 +497,10 @@ export class EditorController implements SlotHost {clearTimeout(this.sessionTimer);const root = this.sessionRoot;if (!root) return;+ if (this.forgottenSessions.has(root)) {+ storeSession(root, null);+ return;+ }const files: Record<string, FileViewState> = Object.fromEntries(this.restoredViews);for (const slot of this.slots.values()) {if (slot.disposed) continue;@@ -510,9 +516,34 @@ export class EditorController implements SlotHost {);}+ /** Drops this window's saved tabs. Later saves keep them dropped until the close is undone. */+ forgetSavedTabs() {+ const root = this.sessionRoot ?? this.openSessionKey();+ if (!root) return;+ this.forgottenSessions.add(root);+ if (this.sessionRoot === root) this.saveSession();+ else storeSession(root, null);+ }++ /** Writes the open tabs again after {@link forgetSavedTabs}, when the close did not happen. */+ keepSavedTabs() {+ const root = this.sessionRoot;+ if (!root || !this.forgottenSessions.delete(root)) return;+ this.saveSession();+ }++ private openSessionKey(): string | null {+ const s = useProject.getState();+ if (s.project?.root) return s.project.root;+ if (s.lightEdit) return LIGHT_EDIT_SESSION;+ return null;+ }+/** Reopens the tabs, splits and carets saved for `root` (after the project opened). */async restoreSession(root: string) {this.sessionRoot = root;+ // A window close dropped this session: the next open starts from the tabs opened now.+ if (this.forgottenSessions.delete(root)) return;const session = loadSession(root);if (!session) return;const state = restoreTabsState(session, fileKey);diff --git a/src/editor/core/index.ts b/src/editor/core/index.tsindex 21ae6ec03..6160fd243 100644--- a/src/editor/core/index.ts+++ b/src/editor/core/index.ts@@ -52,6 +52,8 @@ export function activate(): void | (() => void) {closeInput: (key) => ctrl.closeInput(key),prepareClose: () => ctrl.prepareClose(),cancelClose: () => ctrl.cancelClose(),+ forgetSavedTabs: () => ctrl.forgetSavedTabs(),+ keepSavedTabs: () => ctrl.keepSavedTabs(),documentHistory: (command) => ctrl.documentHistory(command),reformat: async (path) => {const handle = editorsFor(path)[0];diff --git a/src/editor/core/session-close.test.ts b/src/editor/core/session-close.test.tsnew file mode 100644index 000000000..d7faecddd--- /dev/null+++ b/src/editor/core/session-close.test.ts@@ -0,0 +1,99 @@+import { afterEach, describe, expect, it } from "vitest";+import { useProject } from "@/platform/project";+import { EditorController, LIGHT_EDIT_SESSION, openFilePaths, useTabs } from "./controller";+import { createMemoryBackend } from "./backend";+import { initialTabsState } from "./model/tabs";+import { loadSession, storeSession } from "./model/session";++let ctrl: EditorController | null = null;+const initialSettings = useProject.getState().settings;+const PROJECT = "/proj";++afterEach(() => {+ ctrl?.stop();+ ctrl = null;+ useTabs.setState(initialTabsState(), true);+ useProject.setState({ project: null, lightEdit: false, settings: initialSettings } as never);+ for (const key of [LIGHT_EDIT_SESSION, PROJECT]) {+ try {+ localStorage.removeItem(`openidea.editorSession.v1:${key}`);+ } catch {+ /* ignore */+ }+ }+});++function paths() {+ return openFilePaths(useTabs.getState());+}++const flush = () => new Promise((r) => setTimeout(r, 50));++function seed(root: string, path: string) {+ storeSession(root, {+ version: 1,+ layout: { kind: "pane", tabs: [{ path }], active: 0 },+ activePane: 0,+ files: {},+ });+}++describe("editor tabs after the window closes", () => {+ it("does not restore tabs a close dropped, and a later save does not put them back", async () => {+ seed(LIGHT_EDIT_SESSION, "/p/a.ts");+ ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b", "/p/c.ts": "c" }));+ ctrl.start();+ useProject.setState({ project: null, lightEdit: true });+ await ctrl.openFile("/p/b.ts", { focus: true });+ await flush();+ expect(paths().sort()).toEqual(["/p/a.ts", "/p/b.ts"]);++ ctrl.forgetSavedTabs();+ expect(loadSession(LIGHT_EDIT_SESSION)).toBeNull();+ window.dispatchEvent(new Event("pagehide"));+ ctrl.saveSession();+ expect(loadSession(LIGHT_EDIT_SESSION)).toBeNull();++ useProject.setState({ project: null, lightEdit: false });+ await flush();+ useProject.setState({ project: null, lightEdit: true });+ await ctrl.openFile("/p/c.ts", { focus: true });+ await flush();+ expect(paths()).toEqual(["/p/c.ts"]);+ ctrl.saveSession();+ const saved = JSON.stringify(loadSession(LIGHT_EDIT_SESSION));+ expect(saved).toContain("/p/c.ts");+ expect(saved).not.toContain("/p/a.ts");+ });++ it("writes the open tabs again when the close is cancelled", async () => {+ seed(LIGHT_EDIT_SESSION, "/p/a.ts");+ ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" }));+ ctrl.start();+ useProject.setState({ project: null, lightEdit: true });+ await ctrl.openFile("/p/b.ts", { focus: true });+ await flush();+ ctrl.forgetSavedTabs();+ expect(loadSession(LIGHT_EDIT_SESSION)).toBeNull();+ ctrl.keepSavedTabs();+ expect(JSON.stringify(loadSession(LIGHT_EDIT_SESSION))).toContain("/p/b.ts");+ });++ it("drops only the closed window's session", async () => {+ seed(LIGHT_EDIT_SESSION, "/p/a.ts");+ seed(PROJECT, "/proj/main.ts");+ ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/proj/main.ts": "main" }));+ ctrl.start();+ useProject.setState({ project: null, lightEdit: true });+ await flush();+ ctrl.forgetSavedTabs();+ useProject.setState({ project: null, lightEdit: false });+ await flush();+ expect(loadSession(LIGHT_EDIT_SESSION)).toBeNull();+ expect(loadSession(PROJECT)?.layout).toMatchObject({ kind: "pane", tabs: [{ path: "/proj/main.ts" }] });++ useProject.setState({ project: { root: PROJECT, name: "proj" }, lightEdit: false } as never);+ await flush();+ expect(paths()).toEqual(["/proj/main.ts"]);+ });+});diff --git a/src/features/app/__tests__/closeGuard.test.ts b/src/features/app/__tests__/closeGuard.test.tsindex 23e5952bc..31a118ff5 100644--- a/src/features/app/__tests__/closeGuard.test.ts+++ b/src/features/app/__tests__/closeGuard.test.ts@@ -1,5 +1,13 @@import { describe, expect, it, vi } from "vitest";-import { confirmExitEnabled, decideClose, type CloseDeps, type CloseInput } from "../closeGuard";+import {+ closeTabsWithWindowEnabled,+ closeWithoutWelcomeEnabled,+ confirmExitEnabled,+ decideClose,+ returnsToWelcome,+ type CloseDeps,+ type CloseInput,+} from "../closeGuard";import type { MessageRequest as PromptRequest, MessageResult as PromptResult } from "@/workbench/messages";import type { EditorCloseSession } from "@/workbench/contributions";@@ -145,6 +153,25 @@ describe("decideClose", () => {expect(confirmExitEnabled(null)).toBe(false);});+ it("returns to Welcome unless the user chooses to close the last window", () => {+ const on = { general: { closeWithoutWelcome: true } };+ expect(closeWithoutWelcomeEnabled(null)).toBe(false);+ expect(closeWithoutWelcomeEnabled({ general: {} })).toBe(false);+ expect(closeWithoutWelcomeEnabled(on)).toBe(true);+ expect(returnsToWelcome(false, 1, true, null)).toBe(true);+ expect(returnsToWelcome(false, 1, true, { general: {} })).toBe(true);+ expect(returnsToWelcome(false, 1, true, on)).toBe(false);+ expect(returnsToWelcome(true, 1, true, null)).toBe(false);+ expect(returnsToWelcome(false, 2, true, null)).toBe(false);+ expect(returnsToWelcome(false, 1, false, null)).toBe(false);+ });++ it("keeps editor tabs across a close unless the user chooses to drop them", () => {+ expect(closeTabsWithWindowEnabled(null)).toBe(false);+ expect(closeTabsWithWindowEnabled({ general: {} })).toBe(false);+ expect(closeTabsWithWindowEnabled({ general: { closeTabsWithWindow: true } })).toBe(true);+ });+it("includes dirty changes produced while preparing a custom document", async () => {const { d } = deps([{ button: "save", checked: false }]);let text = "old output";diff --git a/src/features/app/__tests__/windowClose.test.ts b/src/features/app/__tests__/windowClose.test.tsnew file mode 100644index 000000000..d14a17bcc--- /dev/null+++ b/src/features/app/__tests__/windowClose.test.ts@@ -0,0 +1,126 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as ipc from "@/platform/ipc";+import { useProject } from "@/platform/project";+import * as services from "@/workbench/contributions";+import { installCloseGuard, type CloseDeps } from "../closeGuard";++const native = vi.hoisted(() => ({+ close: undefined as ((event: { preventDefault: () => void }) => Promise<void>) | undefined,+}));+vi.mock("@tauri-apps/api/window", () => ({+ getAllWindows: async () => [],+ getCurrentWindow: () => ({+ label: "main",+ listen: async () => () => {},+ onCloseRequested: async (callback: typeof native.close) => {+ native.close = callback;+ return () => {};+ },+ }),+}));++const initialProject = useProject.getState();+let uninstall: (() => void) | undefined;+let deps: CloseDeps;+const forget = vi.fn();+const keep = vi.fn();++beforeEach(() => {+ vi.spyOn(ipc, "isTauri").mockReturnValue(true);+ vi.spyOn(ipc, "onIdeEvent").mockReturnValue(() => {});+ vi.spyOn(ipc.commands, "windowCloseContext").mockResolvedValue({ quitting: false, windows: 1 });+ vi.spyOn(ipc.commands, "windowGroupCancelClose").mockResolvedValue(undefined);+ vi.spyOn(ipc.commands, "appCancelQuit").mockResolvedValue(undefined);+ vi.spyOn(ipc.commands, "closeProject").mockResolvedValue(undefined);+ vi.spyOn(services, "maybeEditorService").mockReturnValue({+ forgetSavedTabs: forget,+ keepSavedTabs: keep,+ dirtyDocumentIds: () => [],+ cancelClose: vi.fn(),+ } as never);+ deps = {+ ask: vi.fn(async () => ({ button: "cancel", checked: false })),+ saveAll: vi.fn(async () => {}),+ disableConfirmExit: vi.fn(async () => {}),+ disableConfirmTerminate: vi.fn(async () => {}),+ runningProcesses: vi.fn(async () => []),+ onSaveFailed: vi.fn(),+ };+});++afterEach(() => {+ uninstall?.();+ uninstall = undefined;+ native.close = undefined;+ useProject.setState(initialProject, true);+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++async function close(general: Record<string, boolean>, lightEdit = false) {+ useProject.setState({+ project: lightEdit ? null : { root: "/project", name: "project" },+ lightEdit,+ settings: { general },+ } as never);+ uninstall = installCloseGuard(deps);+ await vi.waitFor(() => expect(native.close).toBeDefined());+ const preventDefault = vi.fn();+ await native.close!({ preventDefault });+ return preventDefault;+}++describe("native window close", () => {+ it.each([false, true])("keeps old sessions with missing settings (LightEdit=%s)", async (lightEdit) => {+ const prevented = await close({}, lightEdit);+ expect(prevented).toHaveBeenCalledOnce();+ expect(ipc.commands.closeProject).toHaveBeenCalledOnce();+ expect(forget).not.toHaveBeenCalled();+ });++ it.each([1, 2])("closes one of %s windows when opted in", async (windows) => {+ vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows });+ const prevented = await close({ closeWithoutWelcome: true, closeTabsWithWindow: true });+ expect(prevented).not.toHaveBeenCalled();+ expect(ipc.commands.closeProject).not.toHaveBeenCalled();+ expect(forget).toHaveBeenCalledOnce();+ });++ it("closes a nonlast window with defaults and keeps its saved tabs", async () => {+ vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });+ const prevented = await close({});+ expect(prevented).not.toHaveBeenCalled();+ expect(ipc.commands.closeProject).not.toHaveBeenCalled();+ expect(forget).not.toHaveBeenCalled();+ });++ it.each([false, true])("keeps tabs after cancelling unsaved changes (close window=%s)", async (closeWindow) => {+ const cancel = vi.fn();+ deps.prepareClose = async () => ({ dirty: 1, discard: vi.fn(), commit: vi.fn(), cancel });+ const prevented = await close({ closeWithoutWelcome: closeWindow, closeTabsWithWindow: true });+ expect(prevented).toHaveBeenCalledOnce();+ expect(cancel).toHaveBeenCalledOnce();+ expect(forget).not.toHaveBeenCalled();+ expect(ipc.commands.closeProject).not.toHaveBeenCalled();+ });++ it("keeps tabs when saving fails", async () => {+ deps.prepareClose = async () => ({ dirty: 1, discard: vi.fn(), commit: vi.fn(), cancel: vi.fn() });+ deps.ask = async () => ({ button: "save", checked: false });+ deps.saveAll = async () => {+ throw new Error("disk full");+ };+ const prevented = await close({ closeWithoutWelcome: true, closeTabsWithWindow: true });+ expect(prevented).toHaveBeenCalledOnce();+ expect(forget).not.toHaveBeenCalled();+ });++ it("restores saved tabs if returning to Welcome fails", async () => {+ vi.mocked(ipc.commands.closeProject).mockRejectedValue(new Error("close failed"));+ const prevented = await close({ closeTabsWithWindow: true });+ expect(prevented).toHaveBeenCalledOnce();+ expect(forget).toHaveBeenCalledOnce();+ expect(keep).toHaveBeenCalledOnce();+ expect(deps.onSaveFailed).toHaveBeenCalledOnce();+ });+});diff --git a/src/features/app/closeGuard.ts b/src/features/app/closeGuard.tsindex 92c1d6599..3c951d257 100644--- a/src/features/app/closeGuard.ts+++ b/src/features/app/closeGuard.ts@@ -7,6 +7,10 @@* still run and `run.confirmTerminate` is on, then Save All / Don't Save / Cancel* when documents have unsaved changes. Quit confirms once, then the backend* closes every window, each of which runs its own checks.+ *+ * The last project or LightEdit window returns to the Welcome screen unless+ * `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 { t } from "@/platform/i18n";@@ -34,6 +38,26 @@ export function confirmExitEnabled(settings: Settings | null | undefined): boolereturn settings?.general?.confirmExit === true;}+/** Last window closes instead of showing Welcome. Only an explicit choice does. */+export function closeWithoutWelcomeEnabled(settings: Settings | null | undefined): boolean {+ return settings?.general?.closeWithoutWelcome === true;+}++/** A closed window does not restore its editor tabs next time. Only an explicit choice does. */+export function closeTabsWithWindowEnabled(settings: Settings | null | undefined): boolean {+ return settings?.general?.closeTabsWithWindow === true;+}++/** The last project or LightEdit window shows Welcome instead of closing. */+export function returnsToWelcome(+ quitting: boolean,+ windows: number,+ hasSession: boolean,+ settings: Settings | null | undefined,+): boolean {+ return !quitting && windows <= 1 && hasSession && !closeWithoutWelcomeEnabled(settings);+}+export interface CloseInput {quitting: boolean;windows: number;@@ -175,9 +199,22 @@ async function processNames(deps: CloseDeps): Promise<string[]> {let closing = false;+/** Drops saved tabs when that setting is on. The result says whether a cancelled close should put them back. */+function forgetTabs(): boolean {+ if (!closeTabsWithWindowEnabled(useProject.getState().settings)) return false;+ maybeEditorService()?.forgetSavedTabs?.();+ return true;+}+async function onCloseRequested(deps: CloseDeps): Promise<boolean> {if (closing) return false;closing = true;+ let forgot = false;+ const undoForget = () => {+ if (!forgot) return;+ forgot = false;+ maybeEditorService()?.keepSavedTabs?.();+ };try {const ctx = await commands.windowCloseContext();if (!(await closeDocumentWindows())) {@@ -185,10 +222,19 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {return false;}const s = useProject.getState();- // Closing the last project (or LightEdit) window closes its project and shows the welcome- // screen (to open another one); closing the welcome screen, or quitting, closes the window.- if (!ctx.quitting && ctx.windows <= 1 && (s.project || s.lightEdit)) {- if (await confirmLeave(deps)) await closeProject();+ // 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)) {+ forgot = forgetTabs();+ try {+ await closeProject();+ // Welcome is showing; keep the tabs dropped.+ forgot = false;+ } catch (e) {+ undoForget();+ throw e;+ }+ }await commands.windowGroupCancelClose();return false;}@@ -205,9 +251,15 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {},deps,);- if (!ok) await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());- return ok;+ if (!ok) {+ await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());+ return false;+ }+ // The window is closing. Drop the tabs now so pagehide cannot write them back.+ forgetTabs();+ return true;} catch (e) {+ undoForget();maybeEditorService()?.cancelClose?.();void commands.windowGroupCancelClose().catch(() => {});deps.onSaveFailed(e);diff --git a/src/features/app/windows.ts b/src/features/app/windows.tsindex 08d1fec0d..8fa1a3dc5 100644--- a/src/features/app/windows.ts+++ b/src/features/app/windows.ts@@ -571,8 +571,9 @@ async function closeThisWindow(): Promise<void> {}/**- * LightEdit: closing its last editor tab closes the window (through the close guard,- * so the last window shows the Welcome screen instead).+ * LightEdit: closing its last editor tab closes the window, through the close guard.+ * The last window returns to Welcome unless "Close the window instead of showing the+ * Welcome screen" is on.*/export function installLightEditAutoClose(closeWindow: () => Promise<void> = closeThisWindow): () => void {const editor = maybeEditorService();diff --git a/src/features/settings/__tests__/behavior.test.ts b/src/features/settings/__tests__/behavior.test.tsindex 9185c194e..1c4e6a060 100644--- a/src/features/settings/__tests__/behavior.test.ts+++ b/src/features/settings/__tests__/behavior.test.ts@@ -69,6 +69,21 @@ describe("appearance & behavior settings", () => {});});+ it("keeps Welcome and saved tabs unless the user turns the new close behaviour on", () => {+ const fresh = validateSettings({});+ expect(fresh.general.closeWithoutWelcome).toBe(false);+ expect(fresh.general.closeTabsWithWindow).toBe(false);+ const on = validateSettings({ general: { closeWithoutWelcome: true, closeTabsWithWindow: true } });+ expect(on.general.closeWithoutWelcome).toBe(true);+ expect(on.general.closeTabsWithWindow).toBe(true);+ expect(+ validateSettings({ general: { closeWithoutWelcome: "yes", closeTabsWithWindow: 1 } } as never).general,+ ).toMatchObject({+ closeWithoutWelcome: false,+ closeTabsWithWindow: false,+ });+ });+it("defaults Show tool window badges to on and honours the stored value", () => {expect(validateAppearanceExtras({}).showToolWindowBadges).toBe(true);expect(validateAppearanceExtras({ showToolWindowBadges: false }).showToolWindowBadges).toBe(false);diff --git a/src/features/settings/model/schema.ts b/src/features/settings/model/schema.tsindex efb0240ca..9146fdb04 100644--- a/src/features/settings/model/schema.ts+++ b/src/features/settings/model/schema.ts@@ -46,7 +46,14 @@ export interface CustomKeymapSettings {export interface ValidSettings extends WorkflowSettings {plugins: Record<string, Record<string, unknown>>;- general: { reopenLastProject: boolean; confirmExit: boolean } & GeneralExtras;+ general: {+ reopenLastProject: boolean;+ confirmExit: boolean;+ /** Last window closes instead of showing the Welcome screen. */+ closeWithoutWelcome: boolean;+ /** Closing a window drops its saved editor tabs. */+ closeTabsWithWindow: boolean;+ } & GeneralExtras;appearance: { theme: ThemeId; accent: string; uiFontSize: number; locale: Locale } & AppearanceExtras;editor: {fontFamily: string;@@ -126,7 +133,13 @@ export { ACCENT_PRESETS } from "@/workbench/theme";export const DEFAULT_SETTINGS: ValidSettings = {plugins: {},- general: { reopenLastProject: true, confirmExit: true, ...DEFAULT_GENERAL_EXTRAS },+ general: {+ reopenLastProject: true,+ confirmExit: true,+ closeWithoutWelcome: false,+ closeTabsWithWindow: false,+ ...DEFAULT_GENERAL_EXTRAS,+ },appearance: { theme: "light", accent: "#3871e1", uiFontSize: 13, locale: "en", ...DEFAULT_APPEARANCE_EXTRAS },editor: {fontFamily: "JetBrains Mono",@@ -225,6 +238,8 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {...validateGeneralExtras(g),reopenLastProject: bool(g.reopenLastProject, d.general.reopenLastProject),confirmExit: bool(g.confirmExit, d.general.confirmExit),+ closeWithoutWelcome: bool(g.closeWithoutWelcome, d.general.closeWithoutWelcome),+ closeTabsWithWindow: bool(g.closeTabsWithWindow, d.general.closeTabsWithWindow),},appearance: {...validateAppearanceExtras(a),diff --git a/src/features/settings/pages/behavior.tsx b/src/features/settings/pages/behavior.tsxindex f7a88d0a0..b1c1e7985 100644--- a/src/features/settings/pages/behavior.tsx+++ b/src/features/settings/pages/behavior.tsx@@ -690,7 +690,7 @@ export const BEHAVIOR_PAGES: PageSpec[] = [title: "System Settings",group: APPEARANCE_GROUP,order: 1,- keywords: ["general", "startup", "exit", "quit", "autosave", "save", "local history"],+ keywords: ["general", "startup", "exit", "quit", "autosave", "save", "local history", "welcome", "editor tabs"],sections: [{title: "Project",@@ -751,7 +751,21 @@ export const BEHAVIOR_PAGES: PageSpec[] = [},{title: "Exit",- options: [{ kind: "toggle", key: "general.confirmExit", label: "Confirm before exiting the IDE" }],+ options: [+ { kind: "toggle", key: "general.confirmExit", label: "Confirm before exiting the IDE" },+ {+ kind: "toggle",+ key: "general.closeWithoutWelcome",+ label: "Close the window instead of showing the Welcome screen",+ hint: "When this is the only window, closing a project or a file closes the window. On macOS, the app stays in the Dock.",+ },+ {+ kind: "toggle",+ key: "general.closeTabsWithWindow",+ label: "Close all editor tabs when the window closes",+ hint: "Files left open are not restored the next time that project or a standalone file is opened.",+ },+ ],},],},diff --git a/src/platform/clientSettings.ts b/src/platform/clientSettings.tsindex 0c33aef46..dd2e4d256 100644--- a/src/platform/clientSettings.ts+++ b/src/platform/clientSettings.ts@@ -10,6 +10,8 @@ export const CLIENT_SETTINGS_KEYS = ["notifications","general.reopenLastProject","general.confirmExit",+ "general.closeWithoutWelcome",+ "general.closeTabsWithWindow","general.openProjectIn","general.updateSource","general.autoCheckUpdates",diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.jsonindex 3fec084a7..4dd7a6971 100644--- a/src/platform/locales/text/en.json+++ b/src/platform/locales/text/en.json@@ -719,6 +719,10 @@"Show Processes": "Show Processes","Open Log in Editor": "Open Log in Editor","Open Container Log in Editor": "Open Container Log in Editor",+ "Close the window instead of showing the Welcome screen": "Close the window instead of showing the Welcome screen",+ "When this is the only window, closing a project or a file closes the window. On macOS, the app stays in the Dock.": "When this is the only window, closing a project or a file closes the window. On macOS, the app stays in the Dock.",+ "Close all editor tabs when the window closes": "Close all editor tabs when the window closes",+ "Files left open are not restored the next time that project or a standalone file is opened.": "Files left open are not restored the next time that project or a standalone file is opened.","Could not read .NET test results: {error}\n": "Could not read .NET test results: {error}\n","Invalid TRX report": "Invalid TRX report",".NET Workspace": ".NET Workspace",diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.jsonindex 4258d180d..dccdf58c9 100644--- a/src/platform/locales/text/zh.json+++ b/src/platform/locales/text/zh.json@@ -597,10 +597,12 @@"Close Tabs to the Right": "关闭右侧标签页","Close Terminal Session": "关闭终端会话","Close Unmodified Tabs": "关闭未修改的标签页",+ "Close all editor tabs when the window closes": "关闭窗口时关闭所有编辑器标签页","Close least recently used files": "关闭最近最少使用的文件","Close non-modified files first": "优先关闭未修改的文件","Close performance overlay": "关闭性能浮层","Close session when it ends": "会话结束时关闭",+ "Close the window instead of showing the Welcome screen": "关闭窗口,而不是显示欢迎屏幕","Closing Policy": "关闭策略","Code": "代码","Code Completion": "代码补全",@@ -1013,6 +1015,7 @@"File templates": "文件模板","File:": "文件:","Files": "文件",+ "Files left open are not restored the next time that project or a standalone file is opened.": "仍打开的文件在下次打开该项目或单独打开文件时不会恢复。","Files to include": "要包括的文件","Files to roll back": "要回滚的文件","Files to shelve": "要搁置的文件",@@ -2750,6 +2753,7 @@"When files are deleted": "删除文件时","When the current tab is closed, activate": "关闭当前标签页时,激活","When the tab limit is reached": "达到标签页限制时",+ "When this is the only window, closing a project or a file closes the window. On macOS, the app stays in the Dock.": "当这是唯一的窗口时,关闭项目或文件会关闭窗口。在 macOS 上,应用仍保留在程序坞中。","Widescreen tool window layout": "宽屏工具窗口布局","Window": "窗口","Words": "单词",diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.tsindex bd535e46c..5e1431f92 100644--- a/src/workbench/contributions.ts+++ b/src/workbench/contributions.ts@@ -593,6 +593,10 @@ export interface EditorService {prepareClose?(): Promise<EditorCloseSession>;/** Backend project/window transition failed after authorization: resume its prepared documents. */cancelClose?(): void;+ /** Drops this window's saved editor tabs so the next open does not restore them. */+ forgetSavedTabs?(): void;+ /** Writes them again when a close is cancelled after {@link forgetSavedTabs}. */+ keepSavedTabs?(): void;/** Edit › Undo / Redo for a focused custom editor that has its own history; false when none takes it. */documentHistory?(command: "undo" | "redo"): boolean;}