Skip to content

Commit 622ffce

Browse files
feat: terminals can activate a Python environment, including conda (#186)
Add VS Code-style Python environment activation for integrated terminals. "Activate Python environment in terminals" (off by default) types the activation command into new and restarted shells. "Python interpreter path" mirrors python.defaultInterpreterPath: empty finds a .venv or venv in the terminal's cwd; otherwise an interpreter or environment folder, with conda environments activated through `conda activate`. Both settings are project-scoped, and the path is also file-backed, so a repository can set "pythonInterpreterPath" in t3.json. Exposed in web, desktop and mobile settings and the MCP environment preferences tools. Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent b33bbf5 commit 622ffce

19 files changed

Lines changed: 707 additions & 5 deletions

File tree

‎apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
SettingsEnvironmentFilterHeader,
2525
} from "./components/SettingsEnvironmentFilterHeader";
2626
import { BranchNamingSettings } from "./components/BranchNamingSettings";
27+
import { PythonEnvironmentSettings } from "./components/PythonEnvironmentSettings";
2728
import { SettingsChoiceRow } from "./components/SettingsChoiceRow";
2829
import { SettingsSection } from "./components/SettingsSection";
2930
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
@@ -47,7 +48,13 @@ const PAGE_TITLES: Record<SettingsPage, string> = {
4748
};
4849

4950
const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettingKey[]> = {
50-
"new-threads": ["defaultThreadEnvMode", "worktreeSubmodules", "defaultRuntimeMode"],
51+
"new-threads": [
52+
"defaultThreadEnvMode",
53+
"worktreeSubmodules",
54+
"defaultRuntimeMode",
55+
"terminalActivatePythonEnvironment",
56+
"pythonInterpreterPath",
57+
],
5158
"source-control": [
5259
"defaultAutoPull",
5360
"removeAgentCreditsOnMerge",
@@ -320,6 +327,19 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
320327
/>
321328
))}
322329
</SettingsSection>
330+
<PythonEnvironmentSettings
331+
key={targets
332+
.map((target) => `${target.environment.environmentId}:${target.projectId}`)
333+
.join(",")}
334+
activate={uniform("terminalActivatePythonEnvironment")}
335+
interpreterPath={
336+
isMixed("pythonInterpreterPath")
337+
? null
338+
: (reference?.settings.pythonInterpreterPath ?? "")
339+
}
340+
disabled={disabledFor("terminalActivatePythonEnvironment")}
341+
onChange={write}
342+
/>
323343
</>
324344
) : null}
325345

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import type { ServerSettingsPatch } from "@t3tools/contracts";
2+
import { useRef } from "react";
3+
import { View } from "react-native";
4+
5+
import { AppText as Text, AppTextInput } from "../../../components/AppText";
6+
import { SettingsSection } from "./SettingsSection";
7+
import { SettingsSwitchRow } from "./SettingsSwitchRow";
8+
9+
export function PythonEnvironmentSettings(props: {
10+
activate: boolean | null;
11+
interpreterPath: string | null;
12+
disabled: boolean;
13+
onChange: (patch: ServerSettingsPatch) => void;
14+
}) {
15+
const pathEdited = useRef(false);
16+
return (
17+
<SettingsSection title="Terminal">
18+
<SettingsSwitchRow
19+
icon="terminal"
20+
label="Activate Python environment"
21+
subtitle="New terminals activate the project's Python environment."
22+
value={props.activate}
23+
disabled={props.disabled}
24+
onValueChange={(value) => props.onChange({ terminalActivatePythonEnvironment: value })}
25+
/>
26+
{props.activate !== false ? (
27+
<View className="gap-2 border-t border-border-subtle px-4 py-3">
28+
<Text className="text-sm text-foreground-muted">
29+
An interpreter or environment folder, such as .venv/bin/python or ~/miniconda3/envs/app.
30+
Leave empty to use the repository's t3.json, or find .venv or venv.
31+
</Text>
32+
<AppTextInput
33+
key={props.interpreterPath}
34+
accessibilityLabel="Python interpreter path"
35+
onChangeText={() => {
36+
pathEdited.current = true;
37+
}}
38+
defaultValue={props.interpreterPath ?? ""}
39+
placeholder={props.interpreterPath === null ? "Mixed" : ".venv or venv"}
40+
editable={!props.disabled}
41+
autoCapitalize="none"
42+
autoCorrect={false}
43+
className="min-h-10 rounded-xl px-3 py-2 text-base text-foreground"
44+
onEndEditing={(event) => {
45+
const value = event.nativeEvent.text.trim();
46+
if (
47+
!props.disabled &&
48+
pathEdited.current &&
49+
(props.interpreterPath === null || value !== props.interpreterPath)
50+
)
51+
// Empty inherits from the next tier, ending at t3.json.
52+
props.onChange({ pythonInterpreterPath: value === "" ? null : value });
53+
pathEdited.current = false;
54+
}}
55+
/>
56+
</View>
57+
) : null}
58+
</SettingsSection>
59+
);
60+
}

‎apps/server/src/mcp/toolkits/environment/handlers.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ export function preferences(settings: ServerSettings) {
1212
defaultThreadEnvMode,
1313
newWorktreesStartFromOrigin,
1414
enableProviderUpdateChecks,
15+
terminalActivatePythonEnvironment,
16+
pythonInterpreterPath,
1517
backgroundActivity,
1618
sourceControlWritingStyle,
1719
} = settings;
@@ -20,6 +22,8 @@ export function preferences(settings: ServerSettings) {
2022
defaultThreadEnvMode,
2123
newWorktreesStartFromOrigin,
2224
enableProviderUpdateChecks,
25+
terminalActivatePythonEnvironment,
26+
pythonInterpreterPath,
2327
backgroundActivity: { profile: backgroundActivity.profile },
2428
sourceControlWritingStyle: {
2529
...sourceControlWritingStyle,

‎apps/server/src/mcp/toolkits/environment/tools.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ const PreferenceFields = {
1818
defaultThreadEnvMode: ServerSettings.fields.defaultThreadEnvMode,
1919
newWorktreesStartFromOrigin: ServerSettings.fields.newWorktreesStartFromOrigin,
2020
enableProviderUpdateChecks: ServerSettings.fields.enableProviderUpdateChecks,
21+
terminalActivatePythonEnvironment: ServerSettings.fields.terminalActivatePythonEnvironment,
22+
pythonInterpreterPath: ServerSettings.fields.pythonInterpreterPath,
2123
backgroundActivity: Schema.Struct({ profile: BackgroundActivityProfileSelection }),
2224
sourceControlWritingStyle: Schema.Struct({
2325
mode: Schema.String,
@@ -59,6 +61,8 @@ const EnvironmentPreferencesTool = Tool.make("t3_environment_preferences_update"
5961
defaultThreadEnvMode: ServerSettingsPatch.fields.defaultThreadEnvMode,
6062
newWorktreesStartFromOrigin: ServerSettingsPatch.fields.newWorktreesStartFromOrigin,
6163
enableProviderUpdateChecks: ServerSettingsPatch.fields.enableProviderUpdateChecks,
64+
terminalActivatePythonEnvironment: ServerSettingsPatch.fields.terminalActivatePythonEnvironment,
65+
pythonInterpreterPath: ServerSettingsPatch.fields.pythonInterpreterPath,
6266
backgroundActivity: Schema.optionalKey(Schema.Struct({ profile: BackgroundActivityProfile })),
6367
sourceControlWritingStyle: ServerSettingsPatch.fields.sourceControlWritingStyle,
6468
}),

‎apps/server/src/server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,8 @@ const layerCheckpointStore = CheckpointStore.layer.pipe(Layer.provide(layerVcsDr
410410
const layerPortScanner = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
411411

412412
const layerTerminal = TerminalManager.layer.pipe(
413+
// Python environment settings resolve the terminal's project.
414+
Layer.provide(Layer.merge(ProjectionStoreV2.layer, ProjectStore.layer)),
413415
Layer.provide(layerPtyAdapter),
414416
Layer.provide(layerPortScanner),
415417
Layer.provide(layerNativeTelemetry),

‎apps/server/src/terminal/Manager.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, it } from "@effect/vitest";
33
import {
4+
DEFAULT_SERVER_SETTINGS,
45
DEFAULT_TERMINAL_ID,
6+
ProjectId,
57
type TerminalAttachStreamEvent,
68
type TerminalEvent,
79
type TerminalMetadataStreamEvent,
@@ -242,6 +244,7 @@ interface CreateManagerOptions {
242244
>[0]["resolveProviderInstanceEnvironment"];
243245
managedBinaryCacheDir?: string;
244246
managedBinaryToolsDir?: string;
247+
pythonEnvironment?: { readonly activate: boolean; readonly interpreterPath: string };
245248
}
246249

247250
interface ManagerFixture {
@@ -266,6 +269,7 @@ const createManager = (
266269
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" });
267270
const logsDir = join(baseDir, "userdata", "logs", "terminals");
268271
const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter();
272+
const pythonEnvironment = options.pythonEnvironment;
269273

270274
const manager = yield* TerminalManager.makeWithOptions({
271275
logsDir,
@@ -290,6 +294,9 @@ const createManager = (
290294
...(options.resolveProviderInstanceEnvironment !== undefined
291295
? { resolveProviderInstanceEnvironment: options.resolveProviderInstanceEnvironment }
292296
: {}),
297+
...(pythonEnvironment !== undefined
298+
? { resolvePythonEnvironment: () => Effect.succeed(pythonEnvironment) }
299+
: {}),
293300
...(options.managedBinaryCacheDir === undefined
294301
? {}
295302
: {
@@ -2001,6 +2008,74 @@ it.layer(
20012008
}),
20022009
);
20032010

2011+
it.effect("activates a project virtual environment in new shells when enabled", () =>
2012+
Effect.gen(function* () {
2013+
const fs = yield* FileSystem.FileSystem;
2014+
const { join } = yield* Path.Path;
2015+
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-venv-" });
2016+
yield* fs.makeDirectory(join(cwd, ".venv", "bin"), { recursive: true });
2017+
yield* fs.writeFileString(join(cwd, ".venv", "bin", "activate"), "");
2018+
const activate = ` source '${join(cwd, ".venv", "bin", "activate")}'\r`;
2019+
2020+
for (const [enabled, expected] of [
2021+
[true, [activate]],
2022+
[false, []],
2023+
] as const) {
2024+
const { manager, ptyAdapter } = yield* createManager(5, {
2025+
shellResolver: () => "/bin/zsh",
2026+
pythonEnvironment: { activate: enabled, interpreterPath: "" },
2027+
}).pipe(Effect.provide(layerWithHostPlatform("darwin")));
2028+
yield* manager.open(openInput({ cwd }));
2029+
expect(ptyAdapter.processes[0]?.writes).toEqual(expected);
2030+
}
2031+
}),
2032+
);
2033+
2034+
it.effect("takes the Python interpreter path from t3.json when no setting names one", () =>
2035+
Effect.gen(function* () {
2036+
const fileSystem = yield* FileSystem.FileSystem;
2037+
const path = yield* Path.Path;
2038+
const checkoutRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-t3json-" });
2039+
yield* fileSystem.writeFileString(
2040+
path.join(checkoutRoot, "t3.json"),
2041+
`{ "pythonInterpreterPath": "envs/app/bin/python" }`,
2042+
);
2043+
const projectId = ProjectId.make("project-1");
2044+
const resolve = (settings: Partial<typeof DEFAULT_SERVER_SETTINGS>) =>
2045+
TerminalManager.resolveTerminalPythonEnvironment({
2046+
fileSystem,
2047+
path,
2048+
settings: {
2049+
...DEFAULT_SERVER_SETTINGS,
2050+
terminalActivatePythonEnvironment: true,
2051+
...settings,
2052+
},
2053+
projectId,
2054+
checkoutRoot,
2055+
});
2056+
2057+
expect(yield* resolve({})).toEqual({
2058+
activate: true,
2059+
interpreterPath: "envs/app/bin/python",
2060+
});
2061+
// The environment value, and a project override over that, outrank the file.
2062+
expect(yield* resolve({ pythonInterpreterPath: "" })).toEqual({
2063+
activate: true,
2064+
interpreterPath: "",
2065+
});
2066+
expect(
2067+
yield* resolve({
2068+
pythonInterpreterPath: "",
2069+
projectSettingsOverrides: { [projectId]: { pythonInterpreterPath: "~/conda" } },
2070+
}),
2071+
).toEqual({ activate: true, interpreterPath: "~/conda" });
2072+
expect(yield* resolve({ terminalActivatePythonEnvironment: false })).toEqual({
2073+
activate: false,
2074+
interpreterPath: "",
2075+
});
2076+
}),
2077+
);
2078+
20042079
it.effect("filters app runtime env variables from terminal sessions", () =>
20052080
Effect.gen(function* () {
20062081
const { manager, ptyAdapter } = yield* createManager(5, {

0 commit comments

Comments
 (0)