Skip to content

Commit 42fc297

Browse files
authored
feat(tui): inherit terminal environment per session (anomalyco#42957)
1 parent 43dd338 commit 42fc297

23 files changed

Lines changed: 310 additions & 7 deletions

File tree

‎packages/cli/src/commands/handlers/default.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,17 @@ import { Updater } from "../../services/updater"
1010
import { UpdatePreflight } from "../../services/update-preflight"
1111
import { Npm } from "@opencode-ai/util/npm"
1212
import { OPENCODE_CHANNEL, OPENCODE_VERSION } from "../../version"
13+
import { Env } from "../../env"
1314

1415
export default Runtime.handler(Commands, (input) =>
1516
Effect.gen(function* () {
1617
const requestedDirectory = Option.getOrUndefined(input.directory)
18+
const requestedServer = Option.getOrUndefined(input.server)
1719
if (requestedDirectory !== undefined) process.chdir(requestedDirectory)
1820
const preflight = UpdatePreflight.make()
1921
yield* Effect.addFinalizer(() => Effect.promise(() => preflight.close()))
2022
const server = yield* ServerConnection.resolve({
21-
server: Option.getOrUndefined(input.server),
23+
server: requestedServer,
2224
standalone: input.standalone,
2325
mismatch: "replace",
2426
onStart: (reason, previousVersion) => {
@@ -75,6 +77,7 @@ export default Runtime.handler(Commands, (input) =>
7577
resolve: (spec) =>
7678
runPromise(npm.add(spec, { subpaths: ["tui"] }).pipe(Effect.map((result) => result.entrypoint))),
7779
},
80+
environment: requestedServer === undefined ? Env.session() : undefined,
7881
terminalHandoff: () => preflight.finish(),
7982
log: (level, message, tags) => {
8083
const effect =

‎packages/cli/src/env.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,13 @@ export const password = Config.redacted("OPENCODE_PASSWORD").pipe(
1212
Config.withDefault(undefined),
1313
)
1414

15+
export function session() {
16+
return Object.fromEntries(
17+
Object.entries(process.env).filter(
18+
(entry): entry is [string, string] =>
19+
entry[1] !== undefined && entry[0] !== "OPENCODE_PASSWORD" && entry[0] !== "OPENCODE_SERVER_PASSWORD",
20+
),
21+
)
22+
}
23+
1524
export * as Env from "./env"

‎packages/cli/src/mini.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { setTimeout } from "node:timers/promises"
55
import { readStdin } from "./util/io"
66
import { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from "./mini-host"
77
import { parseSessionTargetModel, resolveSessionTarget, type SessionTargetPreparation } from "./session-target"
8+
import { Env } from "./env"
89

910
export type MiniCommandInput = {
1011
server: {
@@ -38,6 +39,7 @@ export async function runMini(input: MiniCommandInput) {
3839
const directory = localDirectory()
3940
const connection = createMiniConnection(input.server)
4041
const sdk = connection.sdk
42+
const environment = input.server.reconnect ? Env.session() : undefined
4143
const requested = parseModel(input.model)
4244
const model = requested ? { providerID: requested.providerID, modelID: requested.id } : undefined
4345
const prepare = prepareTarget(input.agent)
@@ -55,6 +57,7 @@ export async function runMini(input: MiniCommandInput) {
5557
fork: input.fork,
5658
model: requested,
5759
agent: input.agent,
60+
environment,
5861
prepare,
5962
signal,
6063
}).catch((error) => {
@@ -89,6 +92,7 @@ export async function runMini(input: MiniCommandInput) {
8992
client,
9093
location: { directory: next.location.directory, workspace: next.location.workspaceID },
9194
agent: next.agent,
95+
environment,
9296
model: next.model
9397
? { providerID: next.model.providerID, id: next.model.modelID, variant: next.variant }
9498
: undefined,

‎packages/cli/src/run/run.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { parseSessionTargetModel, resolveSessionTarget } from "../session-target
99
import { toolInlineInfo } from "@opencode-ai/tui/mini/tool"
1010
import { runNonInteractivePrompt } from "./noninteractive"
1111
import { UI } from "./ui"
12+
import { Env } from "../env"
1213

1314
export type RunCommandInput = {
1415
server: ServerConnection.Resolved
@@ -91,6 +92,7 @@ async function execute(input: RunCommandInput, prepared: Prepared, endpoint: End
9192
? { providerID: explicit.model.providerID, id: explicit.model.modelID, variant: explicit.variant }
9293
: undefined,
9394
agent: input.agent,
95+
environment: input.server.service ? Env.session() : undefined,
9496
prepare: async (next) => {
9597
const selected =
9698
next.model ??

‎packages/cli/src/session-target.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ export async function resolveSessionTarget(input: {
3636
fork?: boolean
3737
model?: ModelRef
3838
agent?: string
39+
environment?: Readonly<Record<string, string>>
3940
prepare: SessionTargetPreparation
4041
signal?: AbortSignal
4142
}): Promise<SessionTarget> {
@@ -70,6 +71,12 @@ export async function resolveSessionTarget(input: {
7071
.catch((error) => {
7172
throw new SessionTargetMutationError(error)
7273
}))
74+
if (input.environment !== undefined && location.workspaceID === undefined)
75+
await input.client.session
76+
.environment({ sessionID: session.id, variables: input.environment }, ...requestOptions(input.signal))
77+
.catch((error) => {
78+
throw new SessionTargetMutationError(error)
79+
})
7380
return {
7481
session,
7582
location,

‎packages/cli/test/env.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { expect, test } from "bun:test"
2+
import { Env } from "../src/env"
3+
4+
test("session environment omits server credentials", () => {
5+
const previousPassword = process.env.OPENCODE_PASSWORD
6+
const previousLegacyPassword = process.env.OPENCODE_SERVER_PASSWORD
7+
const previousValue = process.env.OPENCODE_SESSION_ENV_TEST
8+
process.env.OPENCODE_PASSWORD = "password"
9+
process.env.OPENCODE_SERVER_PASSWORD = "legacy"
10+
process.env.OPENCODE_SESSION_ENV_TEST = "included"
11+
12+
const environment = Env.session()
13+
14+
if (previousPassword === undefined) delete process.env.OPENCODE_PASSWORD
15+
else process.env.OPENCODE_PASSWORD = previousPassword
16+
if (previousLegacyPassword === undefined) delete process.env.OPENCODE_SERVER_PASSWORD
17+
else process.env.OPENCODE_SERVER_PASSWORD = previousLegacyPassword
18+
if (previousValue === undefined) delete process.env.OPENCODE_SESSION_ENV_TEST
19+
else process.env.OPENCODE_SESSION_ENV_TEST = previousValue
20+
21+
expect(environment.OPENCODE_PASSWORD).toBeUndefined()
22+
expect(environment.OPENCODE_SERVER_PASSWORD).toBeUndefined()
23+
expect(environment.OPENCODE_SESSION_ENV_TEST).toBe("included")
24+
})

‎packages/cli/test/session-target.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,26 @@ describe("session target resolver", () => {
5555
expect(target.session.id).toBe("ses_implicit")
5656
})
5757

58+
test("attaches the terminal environment to the resolved local Session", async () => {
59+
const client = OpenCode.make({ baseUrl: "https://opencode.test" })
60+
const selected = session("ses_resume", "/session")
61+
spyOn(client.session, "get").mockResolvedValue(selected)
62+
spyOn(client.location, "get").mockResolvedValue(location("/session"))
63+
const environment = spyOn(client.session, "environment").mockResolvedValue()
64+
65+
await resolveSessionTarget({
66+
client,
67+
session: selected.id,
68+
environment: { PATH: "/terminal/bin" },
69+
prepare,
70+
})
71+
72+
expect(environment).toHaveBeenCalledWith({
73+
sessionID: selected.id,
74+
variables: { PATH: "/terminal/bin" },
75+
})
76+
})
77+
5878
test("prepares a fresh Session at the server Location before creation", async () => {
5979
const client = OpenCode.make({ baseUrl: "https://opencode.test" })
6080
const order: string[] = []

‎packages/client/src/effect/api/api.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -914,6 +914,10 @@ export type Endpoint5_34Input = { readonly sessionID: Session.ID; readonly messa
914914
export type Endpoint5_34Output = SessionMessage.Info
915915
export type SessionMessageOperation<E = never> = (input: Endpoint5_34Input) => Effect.Effect<Endpoint5_34Output, E>
916916

917+
export type Endpoint5_35Input = { readonly sessionID: Session.ID; readonly variables: { readonly [x: string]: string } }
918+
export type Endpoint5_35Output = void
919+
export type SessionEnvironmentOperation<E = never> = (input: Endpoint5_35Input) => Effect.Effect<Endpoint5_35Output, E>
920+
917921
export interface SessionApi<E = never> {
918922
readonly list: SessionListOperation<E>
919923
readonly create: SessionCreateOperation<E>
@@ -958,6 +962,7 @@ export interface SessionApi<E = never> {
958962
readonly interrupt: SessionInterruptOperation<E>
959963
readonly background: SessionBackgroundOperation<E>
960964
readonly message: SessionMessageOperation<E>
965+
readonly environment: SessionEnvironmentOperation<E>
961966
}
962967

963968
export type Endpoint6_0Input = {

‎packages/client/src/effect/generated/client.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ import type {
8686
Endpoint5_33Output,
8787
Endpoint5_34Input,
8888
Endpoint5_34Output,
89+
Endpoint5_35Input,
90+
Endpoint5_35Output,
8991
Endpoint6_0Input,
9092
Endpoint6_0Output,
9193
Endpoint7_0Input,
@@ -610,6 +612,14 @@ const Endpoint5_34 = (raw: RawClient["server.session"]) => (input: Endpoint5_34I
610612
),
611613
)
612614

615+
const Endpoint5_35 = (raw: RawClient["server.session"]) => (input: Endpoint5_35Input) =>
616+
preserveEffect<Endpoint5_35Output>()(
617+
raw["session.environment"]({
618+
params: { sessionID: input["sessionID"] },
619+
payload: { variables: input["variables"] },
620+
}).pipe(Effect.mapError(mapClientError)),
621+
)
622+
613623
const adaptGroup5 = (raw: RawClient["server.session"]) => ({
614624
list: Endpoint5_0(raw),
615625
create: Endpoint5_1(raw),
@@ -639,6 +649,7 @@ const adaptGroup5 = (raw: RawClient["server.session"]) => ({
639649
interrupt: Endpoint5_32(raw),
640650
background: Endpoint5_33(raw),
641651
message: Endpoint5_34(raw),
652+
environment: Endpoint5_35(raw),
642653
})
643654

644655
const Endpoint6_0 = (raw: RawClient["server.message"]) => (input: Endpoint6_0Input) =>

‎packages/client/src/promise/generated/client.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ import type {
8080
SessionBackgroundOutput,
8181
SessionMessageInput,
8282
SessionMessageOutput,
83+
SessionEnvironmentInput,
84+
SessionEnvironmentOutput,
8385
MessageListInput,
8486
MessageListOutput,
8587
ModelListInput,
@@ -896,6 +898,18 @@ export function make(options: ClientOptions) {
896898
},
897899
requestOptions,
898900
).then((value) => value.data),
901+
environment: (input: SessionEnvironmentInput, requestOptions?: RequestOptions) =>
902+
request<SessionEnvironmentOutput>(
903+
{
904+
method: "PUT",
905+
path: `/api/session/${encodeURIComponent(input.sessionID)}/environment`,
906+
body: { variables: input["variables"] },
907+
successStatus: 204,
908+
declaredStatuses: [404, 401, 400],
909+
empty: true,
910+
},
911+
requestOptions,
912+
),
899913
},
900914
message: {
901915
list: (input: MessageListInput, requestOptions?: RequestOptions) =>

0 commit comments

Comments
 (0)