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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
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
13 changes: 10 additions & 3 deletions apps/server/src/codexAppServerManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};

const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
Expand DownExpand Up@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {

describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();

const result = await manager.sendTurn({
sessionId: "sess_1",
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/codexAppServerManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}

const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
Expand All@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
Expand Down
5 changes: 1 addition & 4 deletions apps/server/src/coreServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}

43 changes: 38 additions & 5 deletions apps/server/src/git.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,7 @@ import {
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
Expand DownExpand Up@@ -569,11 +570,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);

const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
Expand DownExpand Up@@ -604,6 +601,42 @@ describe("git integration", () => {
expect(skipped.status).toBe("skipped_up_to_date");
});

it("pulls behind branch and then reports up-to-date", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await using clone = await makeTmpDir();
await git(remote.path, "init --bare");

await initRepoWithCommit(source.path);
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(source.path, `push -u origin ${initialBranch}`);

await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
await git(clone.path, "config user.email 'test@test.com'");
await git(clone.path, "config user.name 'Test'");
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
await git(clone.path, "add CHANGELOG.md");
await git(clone.path, "commit -m 'remote update'");
await git(clone.path, `push origin ${initialBranch}`);

const core = new GitCoreService();
const pulled = await core.pullCurrentBranch(source.path);
expect(pulled.status).toBe("pulled");
expect((await core.statusDetails(source.path)).behindCount).toBe(0);

const skipped = await core.pullCurrentBranch(source.path);
expect(skipped.status).toBe("skipped_up_to_date");
});

it("top-level pullGitBranch rejects when no upstream exists", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
});

it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
Expand Down
133 changes: 120 additions & 13 deletions apps/server/src/git.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,8 @@ import os from "node:os";
import path from "node:path";

import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
Expand All@@ -12,6 +14,8 @@ import {
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
Expand DownExpand Up@@ -90,6 +94,52 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
};
}

function parseNumstatEntries(
stdout: string,
): Array<{ path: string; insertions: number; deletions: number }> {
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
for (const line of stdout.split(/\r?\n/g)) {
if (line.trim().length === 0) continue;
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
const rawPath =
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
if (rawPath.length === 0) continue;
const added = Number.parseInt(addedRaw ?? "0", 10);
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
const renameArrowIndex = rawPath.indexOf(" => ");
const normalizedPath =
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
entries.push({
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
insertions: Number.isFinite(added) ? added : 0,
deletions: Number.isFinite(deleted) ? deleted : 0,
});
}
return entries;
}

function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
return simple.length > 0 ? simple : null;
}

if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
return null;
}

const tabIndex = line.indexOf("\t");
if (tabIndex >= 0) {
const fromTab = line.slice(tabIndex + 1);
const [path] = fromTab.split("\t");
return path?.trim().length ? path.trim() : null;
}

const parts = line.trim().split(/\s+/g);
const path = parts.at(-1) ?? "";
return path.length > 0 ? path : null;
}

function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
Expand DownExpand Up@@ -172,6 +222,7 @@ export class GitCoreService {
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
Expand All@@ -180,15 +231,20 @@ export class GitCoreService {
}

async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
this.gitStdout(cwd, ["diff", "--numstat"]),
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
]);
Comment on lines +234 to +238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium

src/git.ts:233 Running git status and git diff commands concurrently via Promise.all causes index lock contention—both commands try to acquire .git/index.lock, causing intermittent Unable to create index.lock failures. Consider running these commands sequentially, or adding --no-refresh flags to the diff commands.

- const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([- this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),- this.gitStdout(cwd, ["diff", "--numstat"]),- this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),- ]);+ const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([+ this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--numstat"]),+ this.gitStdout(cwd, ["diff", "--no-refresh", "--cached", "--numstat"]),+ ]);

🚀 Want me to fix this? Reply ex: "fix it for me".

🤖 Prompt for AI
In file apps/server/src/git.ts around lines 233-237:
Running `git status` and `git diff` commands concurrently via `Promise.all` causes index lock contention—both commands try to acquire `.git/index.lock`, causing intermittent `Unable to create index.lock` failures. Consider running these commands sequentially, or adding `--no-refresh` flags to the `diff` commands.


let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();

for (const line of stdout.split(/\r?\n/g)) {
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
Expand All@@ -208,13 +264,45 @@ export class GitCoreService {
}
if (line.trim().length > 0 && !line.startsWith("#")) {
hasWorkingTreeChanges = true;
const pathValue = parsePorcelainPath(line);
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
for (const entry of [...stagedEntries, ...unstagedEntries]) {
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
existing.insertions += entry.insertions;
existing.deletions += entry.deletions;
fileStatMap.set(entry.path, existing);
}

let insertions = 0;
let deletions = 0;
const files = Array.from(fileStatMap.entries())
.map(([path, stat]) => {
insertions += stat.insertions;
deletions += stat.deletions;
return { path, insertions: stat.insertions, deletions: stat.deletions };
})
.toSorted((a, b) => a.path.localeCompare(b.path));

for (const filePath of changedFilesWithoutNumstat) {
if (fileStatMap.has(filePath)) continue;
files.push({ path: filePath, insertions: 0, deletions: 0 });
}
files.sort((a, b) => a.path.localeCompare(b.path));

return {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
Expand All@@ -224,21 +312,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);

const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}

const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);

return {
stagedSummary,
Expand DownExpand Up@@ -291,6 +370,29 @@ export class GitCoreService {
};
}

async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch;
if (!branch) {
throw new Error("Cannot pull from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has no upstream configured. Push with upstream first.");
}
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
await executeGit(cwd, ["pull", "--ff-only"], {
timeoutMs: 30_000,
fallbackErrorMessage: "git pull failed",
});
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
const refreshed = await this.statusDetails(cwd);
return gitPullResultSchema.parse({
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
branch,
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
});
}

async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
Expand DownExpand Up@@ -511,6 +613,11 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
return defaultGitCoreService.listBranches(input);
}

export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
}

export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
Expand Down
13 changes: 3 additions & 10 deletions apps/server/src/gitManager.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";

interface FakeGhScenario {
prListSequence?: string[];
Expand DownExpand Up@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}

function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
Expand DownExpand Up@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
Expand Down
Loading