Skip to content
Draft
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
22 changes: 22 additions & 0 deletions apps/code/src/main/services/agent/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import type { FsService } from "../fs/service";
import type { McpAppsService } from "../mcp-apps/service";
import type { PosthogPluginService } from "../posthog-plugin/service";
import type { ProcessTrackingService } from "../process-tracking/service";
import { loadSessionEnvOverrides } from "../session-env/loader";
import type { SleepService } from "../sleep/service";
import type { AgentAuthAdapter, McpToolInstallations } from "./auth-adapter";
import { discoverExternalPlugins } from "./discover-plugins";
Expand Down Expand Up @@ -982,6 +983,27 @@ When creating pull requests, add the following footer at the end of the PR descr
return taskId ? all.filter((s) => s.taskId === taskId) : all;
}

/**
* Resolve env-var overrides set by the SessionStart-style hooks of the most
* recently active agent session for `taskId`.
*
* Used by git/gh operations triggered from the UI (Commit, Create PR) so
* they pick up the same hook env the agent itself sees — most importantly
* the SSH_AUTH_SOCK that Secretive's hook re-points at the Secretive agent
* for commit signing. Returns an empty object when there is no session for
* the task or when no hook output is available.
*/
public async getSessionEnvForTask(
taskId: string,
): Promise<Record<string, string>> {
const candidates = this.listSessions(taskId)
.filter((s) => !!s.config.sessionId)
.sort((a, b) => b.lastActivityAt - a.lastActivityAt);
const session = candidates[0];
if (!session?.config.sessionId) return {};
return loadSessionEnvOverrides(session.config.sessionId);
}

/**
* Get sessions that were interrupted for a specific reason.
* Optionally filter by repoPath to get only sessions for a specific repo.
Expand Down
16 changes: 13 additions & 3 deletions apps/code/src/main/services/git/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ vi.mock("../../utils/logger.js", () => ({
},
}));

import type { AgentService } from "../agent/service";
import type { LlmGatewayService } from "../llm-gateway/service";
import { GitService } from "./service";

Expand All @@ -31,7 +32,10 @@ describe("GitService.getPrChangedFiles", () => {

beforeEach(() => {
vi.clearAllMocks();
service = new GitService({} as LlmGatewayService);
service = new GitService(
{} as LlmGatewayService,
{ getSessionEnvForTask: async () => ({}) } as unknown as AgentService,
);
});

it("flattens paginated GH API results and maps file statuses", async () => {
Expand Down Expand Up @@ -139,7 +143,10 @@ describe("GitService.getGhAuthToken", () => {

beforeEach(() => {
vi.clearAllMocks();
service = new GitService({} as LlmGatewayService);
service = new GitService(
{} as LlmGatewayService,
{ getSessionEnvForTask: async () => ({}) } as unknown as AgentService,
);
});

it("returns the authenticated GitHub CLI token", async () => {
Expand Down Expand Up @@ -197,7 +204,10 @@ describe("GitService.getPrUrlForBranch", () => {

beforeEach(() => {
vi.clearAllMocks();
service = new GitService({} as LlmGatewayService);
service = new GitService(
{} as LlmGatewayService,
{ getSessionEnvForTask: async () => ({}) } as unknown as AgentService,
);
});

it("returns the PR URL for a branch via gh pr list", async () => {
Expand Down
49 changes: 43 additions & 6 deletions apps/code/src/main/services/git/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { inject, injectable } from "inversify";
import { MAIN_TOKENS } from "../../di/tokens";
import { logger } from "../../utils/logger";
import { TypedEventEmitter } from "../../utils/typed-event-emitter";
import type { AgentService } from "../agent/service";
import type { LlmGatewayService } from "../llm-gateway/service";
import { CreatePrSaga } from "./create-pr-saga";
import type {
Expand Down Expand Up @@ -117,10 +118,31 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
constructor(
@inject(MAIN_TOKENS.LlmGatewayService)
private readonly llmGateway: LlmGatewayService,
@inject(MAIN_TOKENS.AgentService)
private readonly agentService: AgentService,
) {
super();
}

/**
* Resolve env-var overrides set by the agent's SessionStart hooks for the
* given task. Used so UI-triggered git/gh operations (Commit, Create PR)
* see the same env (notably `SSH_AUTH_SOCK` re-pointed at Secretive) as
* the agent's bash tool. Returns `undefined` if there's nothing to apply.
*/
private async getSessionEnv(
taskId: string | undefined,
): Promise<Record<string, string> | undefined> {
if (!taskId) return undefined;
try {
const env = await this.agentService.getSessionEnvForTask(taskId);
return Object.keys(env).length > 0 ? env : undefined;
} catch (err) {
log.warn("Failed to load session env for task", { taskId, err });
return undefined;
}
}

private async getStateSnapshot(
directoryPath: string,
options?: {
Expand Down Expand Up @@ -438,6 +460,7 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
branch?: string,
setUpstream = false,
signal?: AbortSignal,
env?: Record<string, string>,
): Promise<PushOutput> {
const saga = new PushSaga();
const result = await saga.run({
Expand All @@ -446,6 +469,7 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
branch: branch || undefined,
setUpstream,
signal,
env,
});
if (!result.success) {
return { success: false, message: result.error };
Expand Down Expand Up @@ -495,6 +519,7 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
directoryPath: string,
remote = "origin",
signal?: AbortSignal,
env?: Record<string, string>,
): Promise<PublishOutput> {
const currentBranch = await getCurrentBranch(directoryPath);
if (!currentBranch) {
Expand All @@ -507,6 +532,7 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
currentBranch,
true,
signal,
env,
);
return {
success: pushResult.success,
Expand Down Expand Up @@ -580,6 +606,8 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
});
};

const sessionEnv = await this.getSessionEnv(input.taskId);

const saga = new CreatePrSaga(
{
getCurrentBranch: (dir) => getCurrentBranch(dir),
Expand All @@ -588,14 +616,16 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
getChangedFilesHead: (dir) => this.getChangedFilesHead(dir),
generateCommitMessage: (dir) =>
this.generateCommitMessage(dir, input.conversationContext),
commit: (dir, msg, opts) => this.commit(dir, msg, opts),
commit: (dir, msg, opts) =>
this.commit(dir, msg, { ...opts, envOverride: sessionEnv }),
getSyncStatus: (dir) => this.getGitSyncStatus(dir),
push: (dir) => this.push(dir),
publish: (dir) => this.publish(dir),
push: (dir) =>
this.push(dir, "origin", undefined, false, undefined, sessionEnv),
publish: (dir) => this.publish(dir, "origin", undefined, sessionEnv),
generatePrTitleAndBody: (dir) =>
this.generatePrTitleAndBody(dir, input.conversationContext),
createPr: (dir, title, body, draft) =>
this.createPrViaGh(dir, title, body, draft),
this.createPrViaGh(dir, title, body, draft, sessionEnv),
onProgress: emitProgress,
},
log,
Expand Down Expand Up @@ -678,6 +708,8 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
allowEmpty?: boolean;
stagedOnly?: boolean;
taskId?: string;
/** Pre-resolved session env. Internal — used by createPr to avoid re-loading. */
envOverride?: Record<string, string>;
},
): Promise<CommitOutput> {
const fail = (msg: string): CommitOutput => ({
Expand All @@ -689,11 +721,15 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {

if (!message.trim()) return fail("Commit message is required");

const { envOverride, ...sagaOptions } = options ?? {};
const env = envOverride ?? (await this.getSessionEnv(options?.taskId));

const saga = new CommitSaga();
const result = await saga.run({
baseDir: directoryPath,
message: message.trim(),
...options,
env,
...sagaOptions,
});

if (!result.success) return fail(result.error);
Expand Down Expand Up @@ -905,6 +941,7 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
title?: string,
body?: string,
draft?: boolean,
env?: Record<string, string>,
): Promise<{ success: boolean; message: string; prUrl: string | null }> {
const prFooter =
"\n\n---\n*Created with [PostHog Code](https://posthog.com/code?ref=pr)*";
Expand All @@ -918,7 +955,7 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
}
if (draft) args.push("--draft");

const result = await execGh(args, { cwd: directoryPath });
const result = await execGh(args, { cwd: directoryPath, env });
if (result.exitCode !== 0) {
return {
success: false,
Expand Down
135 changes: 135 additions & 0 deletions apps/code/src/main/services/session-env/loader.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { loadSessionEnvOverrides } from "./loader";

describe("loadSessionEnvOverrides", () => {
const SESSION_ID = "test-session-id";
let configDir: string;
let sessionDir: string;
let originalConfigDir: string | undefined;

beforeEach(async () => {
configDir = await fs.mkdtemp(path.join(os.tmpdir(), "session-env-test-"));
sessionDir = path.join(configDir, "session-env", SESSION_ID);
await fs.mkdir(sessionDir, { recursive: true });
originalConfigDir = process.env.CLAUDE_CONFIG_DIR;
process.env.CLAUDE_CONFIG_DIR = configDir;
});

afterEach(async () => {
if (originalConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR;
} else {
process.env.CLAUDE_CONFIG_DIR = originalConfigDir;
}
await fs.rm(configDir, { recursive: true, force: true });
});

const writeHook = (name: string, content: string) =>
fs.writeFile(path.join(sessionDir, name), content);

it("returns empty when CLAUDE_CONFIG_DIR is unset", async () => {
delete process.env.CLAUDE_CONFIG_DIR;
expect(await loadSessionEnvOverrides(SESSION_ID)).toEqual({});
});

it("returns empty when session dir does not exist", async () => {
expect(await loadSessionEnvOverrides("missing-session")).toEqual({});
});

it("returns empty when no hook files match", async () => {
await writeHook("ignored.txt", "export FOO=bar\n");
expect(await loadSessionEnvOverrides(SESSION_ID)).toEqual({});
});

it("parses simple export statements from a SessionStart hook", async () => {
await writeHook("sessionstart-hook-0.sh", "export FOO=bar\n");
const overrides = await loadSessionEnvOverrides(SESSION_ID);
expect(overrides.FOO).toBe("bar");
});

it("captures values produced by `printf %q` shell quoting", async () => {
const value = "/Users/alice/Library/foo bar/socket.ssh";
await writeHook(
"sessionstart-hook-0.sh",
`printf 'export SSH_AUTH_SOCK=%q\\n' ${JSON.stringify(value)} | source /dev/stdin\n` +
// also test the expected hook output format directly
`export SSH_AUTH_SOCK='${value}'\n`,
);
const overrides = await loadSessionEnvOverrides(SESSION_ID);
expect(overrides.SSH_AUTH_SOCK).toBe(value);
});

it("merges exports from multiple hook files in sorted order", async () => {
await writeHook("sessionstart-hook-0.sh", "export FIRST=one\n");
await writeHook("sessionstart-hook-1.sh", "export SECOND=two\n");
await writeHook("setup-hook-0.sh", "export THIRD=three\n");
const overrides = await loadSessionEnvOverrides(SESSION_ID);
expect(overrides.FIRST).toBe("one");
expect(overrides.SECOND).toBe("two");
expect(overrides.THIRD).toBe("three");
});

it("ignores files that don't match the SDK hook naming convention", async () => {
await writeHook("setup.sh", "export SHOULD_NOT_LOAD=1\n");
await writeHook("sessionstart-hook-abc.sh", "export ALSO_NO=1\n");
await writeHook("sessionstart-hook-0.sh", "export YES=1\n");
const overrides = await loadSessionEnvOverrides(SESSION_ID);
expect(overrides).toEqual({ YES: "1" });
});

it("does not return vars that already match the parent process env", async () => {
process.env.UNCHANGED_VAR = "same";
await writeHook("sessionstart-hook-0.sh", "export UNCHANGED_VAR=same\n");
try {
const overrides = await loadSessionEnvOverrides(SESSION_ID);
expect(overrides.UNCHANGED_VAR).toBeUndefined();
} finally {
delete process.env.UNCHANGED_VAR;
}
});

it("handles paths with spaces and quotes safely", async () => {
const dirWithSpaces = path.join(configDir, "session-env", "weird id");
await fs.mkdir(dirWithSpaces, { recursive: true });
await fs.writeFile(
path.join(dirWithSpaces, "sessionstart-hook-0.sh"),
"export SPACED=ok\n",
);
const overrides = await loadSessionEnvOverrides("weird id");
expect(overrides.SPACED).toBe("ok");
});

it("returns empty object on bash failure without throwing", async () => {
await writeHook("sessionstart-hook-0.sh", "exit 1\nexport NEVER=set\n");
// sourcing a script that exits cuts the env -0 short, but we should
// gracefully degrade rather than throw.
const overrides = await loadSessionEnvOverrides(SESSION_ID);
expect(overrides.NEVER).toBeUndefined();
});

it("falls back to empty object if bash is missing", async () => {
// Skip this test on systems where bash exists at /bin/bash —
// we only smoke-check that errors are swallowed.
const realPath = process.env.PATH;
process.env.PATH = "";
try {
const overrides = await loadSessionEnvOverrides(SESSION_ID);
// bash may still be found via absolute path; either outcome is fine.
expect(typeof overrides).toBe("object");
} finally {
process.env.PATH = realPath;
}
});

it("does not leak BASH_VERSION or other shell internals", async () => {
await writeHook("sessionstart-hook-0.sh", "export USEFUL=yes\n");
const overrides = await loadSessionEnvOverrides(SESSION_ID);
expect(overrides.BASH_VERSION).toBeUndefined();
expect(overrides.SHLVL).toBeUndefined();
expect(overrides._).toBeUndefined();
expect(overrides.USEFUL).toBe("yes");
});
});
Loading
Loading