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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

### Fixes & Improvements

- **Git commands stay on the folder's own repository.** A host daemon started from a Git hook or with `GIT_DIR` set in its environment no longer runs Git status, file search, worktree, clone or pool preparation against that other repository. The Git panel of a bare repository now reports "not a Git repository" instead of failing. On Windows pool workers, a long creation ID no longer makes preparation fail on Git's path-length limit, and the reported CPU busy time no longer counts interrupt time twice.
- **Reuse unchanged chat Markdown during streaming.** Markdown bodies skip rendering when their props are unchanged, while relevant tool-result changes still refresh their message. Back/forward session navigation requests the selected session instead of downloading the full session list.
- **Listing files in a folder that is not a Git repository no longer leaves a `git` process running in it.** The @-mention and file-search index asks Git first; when the folder is not a repository it now waits for both Git queries to exit before falling back to reading the folder. A leftover `git` process could briefly keep Windows from deleting or renaming that folder.
- **Dollar amounts no longer render as math.** In text such as “$5 and $10”, the span between the two dollar signs turned into glued italic formula text. Single-dollar math now follows Pandoc's rule: the opening `$` must be followed by a non-space, and the closing `$` must be preceded by a non-space and not followed by a digit. `$x^2$` still renders as math.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ there is no live migration or unpublished-work failover. After an uncertain resp
inspect the retained session before explicitly retrying a command that may have run.


### Local worker maintenance (Unix)
### Local worker maintenance

`ompweb host status` prints daemon PID, native version/protocol, welcomed-link readiness,
executable/entrypoint identity and maintenance state without credentials.
Expand Down
2 changes: 1 addition & 1 deletion graphify-out/graph.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions lib/file-index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Dirent } from "fs";
import { readdir } from "node:fs/promises";
import path from "path";
import { buildEntriesFromFiles, filterFileEntries, type FileIndexEntry } from "./file-fuzzy";
import { createChildProcessEnvironment } from "./project-command-env";
import { createGitEnvironment } from "./project-command-env";
import type { WorkspaceIndex } from "./workspace-types";
const execFileAsync = promisify(execFile);

Expand Down Expand Up @@ -69,7 +69,7 @@ async function listWithGit(cwd: string): Promise<FileListing | null> {
const gitOptions = {
timeout: 10_000,
maxBuffer: 64 * 1024 * 1024,
env: createChildProcessEnvironment({ LC_ALL: "C" }),
env: createGitEnvironment({ LC_ALL: "C" }),
};
// --cached lists index entries, including files already removed from the
// working tree. Those would show up as results that 404 the moment anyone
Expand Down
33 changes: 33 additions & 0 deletions lib/git-changes.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,36 @@ test("git status marks attribute files and -diff files get no synthesized patch"
assert.equal(note.supported, true);
assert.match(note.patch, /^\+hi$/m);
});

test("git status reports a bare repository as no worktree and ignores an inherited GIT_DIR", async (t) => {
const { getGitStatus } = await import("./git-changes.ts");
const { execFileSync } = await import("node:child_process");
const fs = await import("node:fs");
const os = await import("node:os");
const path = await import("node:path");
const saved = { GIT_DIR: process.env.GIT_DIR, GIT_CONFIG_GLOBAL: process.env.GIT_CONFIG_GLOBAL, GIT_CONFIG_NOSYSTEM: process.env.GIT_CONFIG_NOSYSTEM };
const root = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), "git-ambient-dir-")));
t.after(() => {
for (const [key, value] of Object.entries(saved)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
fs.rmSync(root, { recursive: true, force: true });
});
process.env.GIT_CONFIG_GLOBAL = "/dev/null";
process.env.GIT_CONFIG_NOSYSTEM = "1";
const bare = path.join(root, "bare.git");
const repo = path.join(root, "repo");
execFileSync("git", ["init", "-q", "--bare", bare]);
execFileSync("git", ["init", "-q", repo]);
fs.writeFileSync(path.join(repo, "note.txt"), "hi\n");

const inBare = await getGitStatus(bare);
assert.equal(inBare.isGitRepository, false, "a bare repository has no worktree to report");

// A daemon started from a Git hook can inherit GIT_DIR; the status must still be the cwd's own repository.
process.env.GIT_DIR = bare;
const status = await getGitStatus(repo);
assert.equal(status.isGitRepository, true);
assert.deepEqual(status.files.map((f) => path.relative(repo, f.filePath)), ["note.txt"]);
});
10 changes: 6 additions & 4 deletions lib/git-changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import fs from "fs";
import path from "path";
import { promisify } from "util";
import { TEXT_PREVIEW_MAX_BYTES } from "./file-types";
import { createChildProcessEnvironment } from "./project-command-env";
import { createGitEnvironment } from "./project-command-env";
import type {
GitCollapseReason,
GitFileDiffResponse,
Expand All @@ -26,7 +26,7 @@ async function git(cwd: string, args: string[], maxBuffer = GIT_STATUS_MAX_BUFFE
const pending = execFileAsync("git", ["-C", cwd, ...args], {
timeout: GIT_TIMEOUT_MS,
maxBuffer,
env: createChildProcessEnvironment({ LC_ALL: "C" }),
env: createGitEnvironment({ LC_ALL: "C" }),
});
if (input !== undefined) {
// git may exit before reading stdin (EPIPE); that failure surfaces through `pending`.
Expand All @@ -36,10 +36,12 @@ async function git(cwd: string, args: string[], maxBuffer = GIT_STATUS_MAX_BUFFE
return (await pending).stdout;
}

/** The toplevel in `cwd`'s own spelling: Git's --show-toplevel can differ in separators, 8.3 names and symlinks. */
/** The worktree toplevel in `cwd`'s own spelling: Git's --show-toplevel can differ in separators, 8.3 names and symlinks.
* Null outside a worktree; a bare repository has a Git directory but no toplevel. */
async function findRepositoryRoot(cwd: string): Promise<string | null> {
try {
return path.resolve(cwd, (await git(cwd, ["rev-parse", "--show-cdup"])).trim());
const [insideWorkTree, cdup = ""] = (await git(cwd, ["rev-parse", "--is-inside-work-tree", "--show-cdup"])).split("\n");
return insideWorkTree === "true" ? path.resolve(cwd, cdup.trim()) : null;
} catch {
return null;
}
Expand Down
4 changes: 2 additions & 2 deletions lib/github-repo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { execFile } from "child_process";
import { promisify } from "util";
import { createChildProcessEnvironment } from "./project-command-env";
import { createGitEnvironment } from "./project-command-env";

const execFileAsync = promisify(execFile);

Expand Down Expand Up @@ -70,7 +70,7 @@ export async function resolveGithubRepo(cwd: string): Promise<string | null> {
const { stdout } = await execFileAsync(
"git",
["-C", cwd, "config", "--get-regexp", "^(remote\\..*\\.(url|gh-resolved)|url\\..*\\.insteadof)$"],
{ timeout: 5_000, env: createChildProcessEnvironment({ LC_ALL: "C" }) },
{ timeout: 5_000, env: createGitEnvironment({ LC_ALL: "C" }) },
);
return pickGithubRepo(stdout);
} catch {
Expand Down
11 changes: 6 additions & 5 deletions lib/hosts/capacity.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -333,13 +333,14 @@ test("the sampler combines leaf and ancestor limits using each ancestor's own me
});

test("Windows samples OS CPU times and available memory without /proc, cgroups or a load average", () => {
const cpu = (busy, idle) => ({ times: { user: busy - 10, nice: 0, sys: 6, irq: 4, idle } });
// Kernel time `sys` includes `irq` on Windows and both rise between samples: `sys` must count, `irq` must not count again.
const cpu = (busy, idle, irq) => ({ times: { user: busy - irq - 2, nice: 0, sys: irq + 2, irq, idle } });
const steps = [
{ cpus: [cpu(100, 900), cpu(100, 900)], free: 8 * GiB },
{ cpus: [cpu(160, 940), cpu(140, 960)], free: 6 * GiB, activeSessions: 1 },
{ cpus: [cpu(100, 900, 4), cpu(100, 900, 4)], free: 8 * GiB },
{ cpus: [cpu(160, 940, 40), cpu(140, 960, 40)], free: 6 * GiB, activeSessions: 1 },
{ cpus: [], free: 6 * GiB },
{ cpus: [cpu(200, 1000), cpu(200, 1000)], free: 5 * GiB },
{ cpus: [cpu(230, 1070), cpu(230, 1070)], free: 5 * GiB, activeSessions: 4 },
{ cpus: [cpu(200, 1000, 40), cpu(200, 1000, 40)], free: 5 * GiB },
{ cpus: [cpu(230, 1070, 60), cpu(230, 1070, 60)], free: 5 * GiB, activeSessions: 4 },
];
const script = `
const os = require("node:os");
Expand Down
3 changes: 2 additions & 1 deletion lib/hosts/capacity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ let previousCounters: CpuCounters | null = null;
function windowsSample(): { current: CpuCounters; resources: EffectiveResources } | null {
let busy = 0, idle = 0;
for (const { times } of cpus()) {
busy += times.user + times.nice + times.sys + times.irq;
// libuv's Windows `sys` is kernel time minus idle, which already includes interrupt time; `irq` repeats it.
busy += times.user + times.nice + times.sys;
idle += times.idle;
}
const available = freemem();
Expand Down
7 changes: 5 additions & 2 deletions lib/hosts/files-owner.integration.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ if (process.platform === "win32") {
const linkRoute = await import("../../app/api/hosts/link/route.ts");
const hub = await import("./hub.ts");
const { createHost, rotateLocalHostToken } = await import("./registry.ts");
const { sessionWorktreeName } = await import("../pooled-projects.ts");
const { hostSessions, listSessionsAllHosts } = await import("./session-index.ts");
const { getRpcSession, startRpcSession } = await import("../rpc-manager.ts");
const { allowFileRoot } = await import("../file-access.ts");
Expand Down Expand Up @@ -329,8 +330,10 @@ test("a real live session browses its actual cwd before any lazy transcript or s

test("durable real owner metadata keeps an unpublished workspace browsable after its live wrapper is gone", async (t) => {
const creationId = "native-files-journal";
const cwd = join(ownerA.home, ".project_worktrees", "session", creationId);
git(ownerA.project, "worktree", "add", "-b", `session/${creationId}`, "--", cwd, "HEAD");
// Named as preparation names it: a Windows clone root gets a digest name for this 20-character ID.
const name = sessionWorktreeName(ownerA.project, creationId);
const cwd = join(ownerA.home, ".project_worktrees", "session", name);
git(ownerA.project, "worktree", "add", "-b", `session/${name}`, "--", cwd, "HEAD");
writeFileSync(join(cwd, "unpublished.txt"), "owner-a durable unpublished");
const started = await startRpcSession("", "", cwd, undefined, false, null, undefined, hub.getHost(ownerA.hostId));
t.after(() => started.session.destroyAndWait());
Expand Down
4 changes: 3 additions & 1 deletion lib/hosts/host-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ async function createWindowsHostControlServer(control: (command: HostControlComm
await closed.promise;
throw error;
} finally {
try { unlinkSync(temporary); } catch (error) { if (errno(error) !== "ENOENT") throw error; }
// The descriptor is already published or this start already failed: a leftover temporary file is
// harmless, so its removal must not strand a listening pipe behind a rejected start.
try { unlinkSync(temporary); } catch { /* best effort */ }
}
let closing: Promise<void> | undefined;
return {
Expand Down
4 changes: 2 additions & 2 deletions lib/hosts/pool-starts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, re
import { dirname, join } from "node:path";
import { getAgentDir } from "../omp/paths";
import { RpcCommandError } from "../omp/rpc-process";
import type { PreparedPoolProject } from "../pooled-projects";
import { sessionWorktreeName, type PreparedPoolProject } from "../pooled-projects";
import { isValidSessionId } from "../session-file-references-core";
import { isRecord } from "../type-guards";
import type { ProjectLaunchConfig } from "../types";
Expand Down Expand Up @@ -91,7 +91,7 @@ function fingerprint(value: unknown): string { return createHash("sha256").updat
function absolute(path: unknown): path is string { return typeof path === "string" && !path.includes("\0") && pathApi(path).isAbsolute(path) && pathApi(path).normalize(path) === path; }
function creationCwd(cloneRoot: string, creationId: string): string {
const path = pathApi(cloneRoot);
return path.join(path.dirname(cloneRoot), `.${path.basename(cloneRoot)}_worktrees`, "session", creationId);
return path.join(path.dirname(cloneRoot), `.${path.basename(cloneRoot)}_worktrees`, "session", sessionWorktreeName(cloneRoot, creationId));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

function readJournal(): Journal {
Expand Down
4 changes: 2 additions & 2 deletions lib/hosts/workspace-clone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
import { lstat, mkdir, mkdtemp, rename, rm, rmdir } from "node:fs/promises";
import { join } from "node:path";
import { cloneDirectoryName, type CloneFrame, type CloneProgress } from "../git-clone";
import { createChildProcessEnvironment } from "../project-command-env";
import { createGitEnvironment } from "../project-command-env";
import { HostOpError } from "./link-protocol";
import { authorizeWorkspaceDirectory, grantWorkspaceRoot } from "./workspace-roots";

Expand All @@ -24,7 +24,7 @@ function runGitClone(url: string, target: string, signal: AbortSignal, output: (
return new Promise((resolve) => {
const child = spawn("git", ["clone", "--progress", "--", url, target], {
stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true,
env: createChildProcessEnvironment({ GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", SSH_ASKPASS: "", GIT_ALLOW_PROTOCOL: "https:ssh" }),
env: createGitEnvironment({ GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", SSH_ASKPASS: "", GIT_ALLOW_PROTOCOL: "https:ssh" }),
});
let escalation: NodeJS.Timeout | undefined;
const kill = (force: boolean) => {
Expand Down
3 changes: 2 additions & 1 deletion lib/omp/mcp-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { basename, dirname, join, relative, resolve, sep } from "path";
import { stripAnsi } from "../ansi";
import { getAgentDir } from "./paths";
import { isRecord } from "../type-guards";
import { createGitEnvironment } from "../project-command-env";

const MAX_MCP_CONFIG_BYTES = 512 * 1024;
const MAX_DISCOVERED_MCP_CONFIG_BYTES = 5 * 1024 * 1024;
Expand Down Expand Up @@ -183,7 +184,7 @@ function projectRoot(cwd: string): string {
if (cached && cached.expiresAt > Date.now()) return cached.root;
let root: string;
try {
root = resolve(execFileSync("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 }).trim());
root = resolve(execFileSync("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "ignore"], timeout: 10_000, env: createGitEnvironment() }).trim());
} catch {
// Transient git failure (hang, timeout, sick mount): fall back to the cwd
// but do NOT cache it — a cached fallback would aim MCP reads/writes at
Expand Down
44 changes: 34 additions & 10 deletions lib/pooled-projects.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,27 @@ function rejected(result) {
const worktree = (f, id = "creation-1") => join(f.workers, ".registered-project_worktrees", "session", id);

// Tests in a file run serially: each owns its Git config and restores process.env before the next.
const { preparePoolProject } = await import("./pooled-projects.ts");
const { preparePoolProject, sessionWorktreeName } = await import("./pooled-projects.ts");

test("fixture Git cannot write an ambient outside repository or index", () => hostileGitEnvironment(() => fixture(async (f) => {
const value = prepared(await preparePoolProject(f.input));
// The hostile variables are set inside the fixture, which otherwise clears every GIT_ variable first.
test("preparation ignores an ambient Git repository, index, worktree and config", () => fixture(async (f) => {
let value;
await hostileGitEnvironment(async () => { value = prepared(await preparePoolProject(f.input)); });
// Checked after the hostile environment is restored: this test's own git would obey it.
assert.equal(readFileSync(join(value.cwd, "tracked.txt"), "utf8"), "committed\n");
})));
// Canonical on both sides: Git spells Windows paths with forward slashes and long names, Node with 8.3 short names.
const commonDir = git(value.cwd, "rev-parse", "--path-format=absolute", "--git-common-dir");
assert.equal(realpathSync.native(commonDir), realpathSync.native(join(f.cloneRoot, ".git")));
}));

test("a clone configured as bare is not an independent repository", () => fixture(async (f) => {
git(f.root, "clone", f.origin, f.cloneRoot);
git(f.cloneRoot, "config", "core.bare", "true");
const result = await preparePoolProject(f.input);
rejected(result);
assert.equal(result.code, "pool_clone_conflict");
assert.equal(existsSync(worktree(f)), false);
}));

test("clones a registered origin and creates an external session branch", () => fixture(async (f) => {
const value = prepared(await preparePoolProject(f.input));
Expand Down Expand Up @@ -275,14 +290,23 @@ test("unpublished local refs do not become worker session bases", () => fixture(

test("accepts opaque creation IDs including underscore at the 128-character boundary", () => fixture(async (f) => {
const creationId = `request_${"a".repeat(120)}`;
// Git for Windows refuses a GIT_DIR of PATH_MAX - 40 (220) characters or more, and a linked worktree's is
// <clone>\.git\worktrees\<id>: the 128-character ID leaves 76 for the clone root, which the temp fixture path exceeds.
const cloneRoot = join(f.root, "p");
const value = prepared(await preparePoolProject({ ...f.input, cloneRoot, creationId }));
assert.equal(value.cwd, join(f.root, ".p_worktrees", "session", creationId));
assert.equal(git(value.cwd, "branch", "--show-current"), `session/${creationId}`);
// The fixture's long temp clone root is kept on purpose: on Windows, Git refuses a worktree GIT_DIR of 220+
// characters, so a long ID must not lengthen the worktree's name there.
const name = process.platform === "win32" ? sessionWorktreeName(f.cloneRoot, creationId) : creationId;
const value = prepared(await preparePoolProject({ ...f.input, creationId }));
assert.equal(value.cwd, worktree(f, name));
assert.equal(git(value.cwd, "branch", "--show-current"), `session/${name}`);
}));

test("Windows workers name a long creation's worktree by a short digest; POSIX workers keep the ID", () => {
const long = `request_${"a".repeat(120)}`;
const windows = sessionWorktreeName("C:\\pool\\project", long);
assert.match(windows, /^\+[0-9a-f]{16}$/);
assert.equal(sessionWorktreeName("C:\\pool\\project", `request_${"b".repeat(120)}`) === windows, false);
assert.equal(sessionWorktreeName("C:\\pool\\project", "creation-1"), "creation-1");
assert.equal(sessionWorktreeName("/srv/pool/project", long), long);
});

test("unsafe origins and IDs cannot create paths or escape the worker root", () => fixture(async (f) => {
for (const change of [
{ origin: `file://${f.remote}` },
Expand Down
Loading
Loading