Skip to content

Add notebook.workingDirectory setting #8558

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Aug 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#
# Copyright (C) 2023-2024 Posit Software, PBC. All rights reserved.
# Copyright (C) 2023-2025 Posit Software, PBC. All rights reserved.
# Licensed under the Elastic License 2.0. See LICENSE.txt for license information.
#

Expand All @@ -11,7 +11,6 @@
import threading
import warnings
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union, cast

from comm.base_comm import BaseComm
Expand Down Expand Up @@ -248,7 +247,7 @@ class HelpTopicRequest:
class PositronInitializationOptions:
"""Positron-specific language server initialization options."""

notebook_path: Optional[Path] = attrs.field(default=None)
working_directory: Optional[str] = attrs.field(default=None)


class PositronJediLanguageServerProtocol(JediLanguageServerProtocol):
Expand Down Expand Up @@ -285,10 +284,7 @@ def lsp_initialize(self, params: InitializeParams) -> InitializeResult:
server.show_message_log(msg, msg_type=MessageType.Error)
initialization_options = PositronInitializationOptions()

# If a notebook path was provided, set the project path to the notebook's parent.
# See https://github.com/posit-dev/positron/issues/5948.
notebook_path = initialization_options.notebook_path
path = notebook_path.parent if notebook_path else self._server.workspace.root_path
path = initialization_options.working_directory or self._server.workspace.root_path

# Create the Jedi Project.
# Note that this overwrites a Project already created in the parent class.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#
# Copyright (C) 2023-2024 Posit Software, PBC. All rights reserved.
# Copyright (C) 2023-2025 Posit Software, PBC. All rights reserved.
# Licensed under the Elastic License 2.0. See LICENSE.txt for license information.
#

Expand Down Expand Up @@ -103,7 +103,7 @@ def _reduce_debounce_time(monkeypatch):
def create_server(
namespace: Optional[Dict[str, Any]] = None,
root_path: Optional[Path] = None,
notebook_path: Optional[Path] = None,
working_directory: Optional[str] = None,
) -> PositronJediLanguageServer:
# Create a server.
server = create_positron_server()
Expand All @@ -128,7 +128,7 @@ def create_server(
# to test deserialization too.
"positron": cattrs.unstructure(
PositronInitializationOptions(
notebook_path=notebook_path,
working_directory=working_directory,
)
),
},
Expand Down Expand Up @@ -476,7 +476,7 @@ def assert_has_path_completion(
expected_completion: str,
chars_from_end=1,
root_path: Optional[Path] = None,
notebook_path: Optional[Path] = None,
working_directory: Optional[str] = None,
):
# Replace separators for testing cross-platform.
source = source.replace("/", os.path.sep)
Expand All @@ -486,7 +486,7 @@ def assert_has_path_completion(
if os.name == "nt":
expected_completion = expected_completion.replace("/", "\\" + os.path.sep)

server = create_server(root_path=root_path, notebook_path=notebook_path)
server = create_server(root_path=root_path, working_directory=working_directory)
text_document = create_text_document(server, TEST_DOCUMENT_URI, source)
character = len(source) - chars_from_end
completions = _completions(server, text_document, character)
Expand Down Expand Up @@ -721,14 +721,31 @@ def test_notebook_path_completions(tmp_path) -> None:
notebook_parent = tmp_path / "notebooks"
notebook_parent.mkdir()

notebook_path = notebook_parent / "notebook.ipynb"

# Create a file in the notebook's parent.
file_to_complete = notebook_parent / "data.csv"
file_to_complete.write_text("")

assert_has_path_completion(
'""', file_to_complete.name, root_path=tmp_path, notebook_path=notebook_path
'""', file_to_complete.name, root_path=tmp_path, working_directory=str(notebook_parent)
)


def test_notebook_path_completions_different_wd(tmp_path) -> None:
notebook_parent = tmp_path / "notebooks"
notebook_parent.mkdir()

# Make a different working directory.
working_directory = tmp_path / "different-working-directory"
working_directory.mkdir()

# Create files in the notebook's parent and the working directory.
bad_file = notebook_parent / "bad-data.csv"
bad_file.write_text("")
good_file = working_directory / "good-data.csv"
good_file.write_text("")

assert_has_path_completion(
'""', good_file.name, root_path=tmp_path, working_directory=working_directory
)


Expand Down
6 changes: 3 additions & 3 deletions extensions/positron-python/src/client/positron/lsp.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*---------------------------------------------------------------------------------------------
* Copyright (C) 2023-2024 Posit Software, PBC. All rights reserved.
* Copyright (C) 2023-2025 Posit Software, PBC. All rights reserved.
* Licensed under the Elastic License 2.0. See LICENSE.txt for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
Expand Down Expand Up @@ -90,7 +90,7 @@ export class PythonLsp implements vscode.Disposable {
return out.promise;
};

const { notebookUri } = this._metadata;
const { notebookUri, workingDirectory } = this._metadata;

// If this client belongs to a notebook, set the document selector to only include that notebook.
// Otherwise, this is the main client for this language, so set the document selector to include
Expand Down Expand Up @@ -127,7 +127,7 @@ export class PythonLsp implements vscode.Disposable {
// If this server is for a notebook, set the notebook path option.
if (notebookUri) {
this._clientOptions.initializationOptions.positron = {
notebook_path: notebookUri.fsPath,
working_directory: workingDirectory,
};
}

Expand Down
17 changes: 4 additions & 13 deletions extensions/positron-supervisor/src/KallichoreSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,19 +330,10 @@ export class KallichoreSession implements JupyterLanguageRuntimeSession {
this._kernelSpec = kernelSpec;
const varActions = await this.buildEnvVarActions(false);

// Prepare the working directory; use the workspace root if available,
// otherwise the home directory
let workingDir = vscode.workspace.workspaceFolders?.[0].uri.fsPath || os.homedir();

// If we have a notebook URI, use its parent directory as the working
// directory instead. Note that not all notebooks have valid on-disk
// URIs since they may be transient or not yet saved; for these, we fall
// back to the workspace root or home directory.
if (this.metadata.notebookUri?.fsPath) {
const notebookPath = this.metadata.notebookUri.fsPath;
if (fs.existsSync(notebookPath)) {
workingDir = path.dirname(notebookPath);
}
let workingDir = this.metadata.workingDirectory;
if (!workingDir) {
// Use the workspace root if available, otherwise the home directory
workingDir = vscode.workspace.workspaceFolders?.[0].uri.fsPath || os.homedir();
}

// Form the command-line arguments to the kernel process
Expand Down
3 changes: 3 additions & 0 deletions src/positron-dts/positron.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,9 @@ declare module 'positron' {

/** The URI of the notebook document associated with the session, if any */
readonly notebookUri?: vscode.Uri;

/** The starting working directory of the session, if any */
readonly workingDirectory?: string;
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/vs/workbench/api/common/configurationExtensionPoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const IGNORED_JUPYTER_CONFIGURATION_PROPERTIES = new Set([
'jupyter.interactiveWindow.textEditor.executeSelection',
'jupyter.interactiveWindow.textEditor.magicCommandsAsComments',
'jupyter.interactiveWindow.viewColumn',
'jupyter.notebookFileRoot',
]);
// --- End Positron ---
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
Expand Down
12 changes: 12 additions & 0 deletions src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import { IModelService } from '../../../../editor/common/services/model.js';
import { ILanguageSelection, ILanguageService } from '../../../../editor/common/languages/language.js';
import { ITextModelContentProvider, ITextModelService } from '../../../../editor/common/services/resolverService.js';
import * as nls from '../../../../nls.js';
// --- Start Positron ---
// eslint-disable-next-line no-duplicate-imports
import { ConfigurationScope } from '../../../../platform/configuration/common/configurationRegistry.js';
// --- End Positron ---
import { Extensions, IConfigurationPropertySchema, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js';
import { SyncDescriptor } from '../../../../platform/instantiation/common/descriptors.js';
import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js';
Expand Down Expand Up @@ -1311,6 +1315,14 @@ configurationRegistry.registerConfiguration({
type: 'string',
default: '',
tags: ['notebookLayout']
},
// --- Start Positron ---
[NotebookSetting.workingDirectory]: {
markdownDescription: nls.localize('notebook.workingDirectory', "Default working directory for notebook kernels. Supports [variables](https://code.visualstudio.com/docs/reference/variables-reference) like `${workspaceFolder}`. If this setting doesn't resolve to an existing directory, it defaults to the notebook file's directory. Any change to this setting will apply to future opened notebooks."),
type: 'string',
default: '',
scope: ConfigurationScope.RESOURCE
}
// --- End Positron ---
}
});
3 changes: 3 additions & 0 deletions src/vs/workbench/contrib/notebook/common/notebookCommon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,9 @@ export const NotebookSetting = {
outputBackupSizeLimit: 'notebook.backup.sizeLimit',
multiCursor: 'notebook.multiCursor.enabled',
markupFontFamily: 'notebook.markup.fontFamily',
// --- Start Positron ---
workingDirectory: 'notebook.workingDirectory',
// --- End Positron ---
} as const;

export const enum CellStatusbarAlignment {
Expand Down
84 changes: 82 additions & 2 deletions src/vs/workbench/services/runtimeSession/common/runtimeSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ import { INotificationService, Severity } from '../../../../platform/notificatio
import { localize } from '../../../../nls.js';
import { UiClientInstance } from '../../languageRuntime/common/languageRuntimeUiClient.js';
import { IWorkbenchEnvironmentService } from '../../environment/common/environmentService.js';
import { IConfigurationResolverService } from '../../configurationResolver/common/configurationResolver.js';
import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js';
import { NotebookSetting } from '../../../contrib/notebook/common/notebookCommon.js';
import { IFileService } from '../../../../platform/files/common/files.js';
import { dirname } from '../../../../base/common/path.js';

/**
* The maximum number of active sessions a user can have running at a time.
Expand Down Expand Up @@ -170,7 +175,10 @@ export class RuntimeSessionService extends Disposable implements IRuntimeSession
@IExtensionService private readonly _extensionService: IExtensionService,
@IStorageService private readonly _storageService: IStorageService,
@IUpdateService private readonly _updateService: IUpdateService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IConfigurationResolverService private readonly _configurationResolverService: IConfigurationResolverService,
@IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService,
@IFileService private readonly _fileService: IFileService,
) {

super();
Expand Down Expand Up @@ -387,6 +395,70 @@ export class RuntimeSessionService extends Disposable implements IRuntimeSession
return Array.from(this._activeSessionsBySessionId.values());
}

/**
* Validates that a path is an existing directory.
*
* @param path The path to validate
* @returns A promise that resolves to true if the path is a directory and exists,
* false otherwise.
*/
private async isValidDirectory(path: string): Promise<boolean> {
try {
const stat = await this._fileService.stat(URI.file(path));
if (!stat.isDirectory) {
this._logService.warn(`${NotebookSetting.workingDirectory}: Path '${path}' exists but is not a directory`);
return false;
}
return true;
} catch (error) {
this._logService.warn(`${NotebookSetting.workingDirectory}: Path '${path}' does not exist or is not accessible:`, error);
return false;
}
}

/**
* Resolves the working directory for a notebook based on its URI and the setting.
* If the setting doesn't resolve to an existing directory, use the notebook's directory.
* If the directory doesn't exist, return undefined.
*
* @param notebookUri The URI of the notebook
* @returns The resolved working directory or undefined if it doesn't exist
*/
private async resolveNotebookWorkingDirectory(notebookUri: URI): Promise<string | undefined> {
// The default value is the notebook's parent directory, if it exists.
let defaultValue: string | undefined;
const notebookParent = dirname(notebookUri.fsPath);
if (await this.isValidDirectory(notebookParent)) {
defaultValue = notebookParent;
}

const configValue = this._configurationService.getValue<string>(
NotebookSetting.workingDirectory, { resource: notebookUri }
);
if (!configValue || configValue.trim() === '') {
return defaultValue;
}
const workspaceFolder = this._workspaceContextService.getWorkspaceFolder(notebookUri);

// Resolve the variables in the setting
let resolvedValue: string;
try {
resolvedValue = await this._configurationResolverService.resolveAsync(
workspaceFolder || undefined, configValue
);
} catch (error) {
this._logService.warn(`${NotebookSetting.workingDirectory}: Failed to resolve variables in '${configValue}':`, error);
return defaultValue;
}

// Check if the result is a directory that exists
if (await this.isValidDirectory(resolvedValue)) {
return resolvedValue;
} else {
return defaultValue;
}
}

/**
* Select a session for the provided runtime.
*
Expand Down Expand Up @@ -1535,10 +1607,18 @@ export class RuntimeSessionService extends Disposable implements IRuntimeSession
}

const sessionId = this.generateNewSessionId(runtimeMetadata, sessionMode === LanguageRuntimeSessionMode.Notebook);

// Resolve the working directory configuration
let workingDirectory: string | undefined;
if (notebookUri) {
workingDirectory = await this.resolveNotebookWorkingDirectory(notebookUri);
}

const sessionMetadata: IRuntimeSessionMetadata = {
sessionId,
sessionMode,
notebookUri,
workingDirectory,
createdTimestamp: Date.now(),
startReason: source
};
Expand Down Expand Up @@ -1645,7 +1725,7 @@ export class RuntimeSessionService extends Disposable implements IRuntimeSession
* @param runtime The runtime to get the manager for.
* @returns The session manager that manages the runtime.
*
* Throws an errror if no session manager is found for the runtime.
* Throws an error if no session manager is found for the runtime.
*/
private async getManagerForRuntime(runtime: ILanguageRuntimeMetadata): Promise<ILanguageRuntimeSessionManager> {
// Look for the session manager that manages the runtime.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ export interface IRuntimeSessionMetadata {
/** The notebook associated with the session, if any */
readonly notebookUri: URI | undefined;

/** The starting working directory of the session, if any */
readonly workingDirectory?: string;

/**
* A timestamp (in milliseconds since the Epoch) representing the time at
* which the runtime session was created.
Expand Down
Loading
Loading