Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

tech(WIN/DEPS): bash unter Windows deterministisch aufloesen + Arbeitsbaum-Pin

David87658903646b
diff --git a/scripts/build-llama.sh b/scripts/build-llama.sh
index 81254783..7cfb00c2 100755
--- a/scripts/build-llama.sh
+++ b/scripts/build-llama.sh
@@ -30,9 +30,10 @@ set -euo pipefail
# point b9949 at different code tomorrow. This script builds the binary that
# ships inside the installer and is code-signed with the app, so "whatever the
# tag names on the day CI runs" is not a supply chain we can stand behind.
-# LLAMA_TAG stays as the readable name and as the cross-check: the checkout is
-# verified against LLAMA_COMMIT on every run, cache hit included, and the build
-# stops if the two ever disagree.
+# LLAMA_TAG stays as the readable name and as the cross-check: on every run,
+# cache hit included, ensure_src asserts BOTH that HEAD is LLAMA_COMMIT and
+# that the working tree carries no change against it, and the build stops if
+# either fails.
#
# To bump, resolve the tag yourself and paste BOTH — llama.cpp tags are build
# numbers and upstream SKIPS numbers whose CI failed, so the tag must exist:
@@ -138,6 +139,30 @@ ensure_src() {
have="$(git -C "$SRC_DIR" rev-parse HEAD)"
[ "$have" = "$LLAMA_COMMIT" ] \
|| die "llama.cpp checkout is at $have, expected $LLAMA_COMMIT ($LLAMA_TAG) — upstream tag moved, or the build cache is stale"
+ assert_clean_tree
+}
+
+# rev-parse only proves where HEAD POINTS. cmake does not compile HEAD, it
+# compiles the WORKING TREE under $SRC_DIR — and a restored cache is a tarball
+# somebody else produced, in which the files can say anything while .git/HEAD
+# still names the pinned SHA. Verifying the pointer and calling that a verified
+# source tree was the whole gap.
+#
+# `git status` closes it: the index is force-refreshed so nothing rides on a
+# stale stat cache, and then any tracked file whose CONTENT differs from the
+# pinned commit, and any untracked file that is not covered by llama.cpp's own
+# .gitignore, makes the build stop. Together with the SHA check above that is
+# the statement the comment always claimed: what gets compiled is the tree the
+# pinned commit names.
+#
+# Ignored paths are deliberately not in scope — the cmake build directory lives
+# outside $SRC_DIR, so nothing in the ignore set reaches the compiler.
+assert_clean_tree() {
+ git -C "$SRC_DIR" update-index -q --really-refresh >/dev/null 2>&1 || true
+ local dirty
+ dirty="$(git -C "$SRC_DIR" status --porcelain --untracked-files=all 2>/dev/null || true)"
+ [ -z "$dirty" ] || die "llama.cpp source tree does not match $LLAMA_COMMIT ($LLAMA_TAG) — the checkout carries local changes, so the build would not be the pinned source:
+$dirty"
}
# sha256 of a file, or "" where no hasher is on PATH. macOS ships `shasum`,
diff --git a/src/api/__tests__/bash-interpreter.ts b/src/api/__tests__/bash-interpreter.ts
new file mode 100644
index 00000000..4ed96f8c
--- /dev/null
+++ b/src/api/__tests__/bash-interpreter.ts
@@ -0,0 +1,115 @@
+/**
+ * Which `bash` a test may hand to execFileSync.
+ *
+ * Not a test itself — vitest only collects `*.test.ts` (see vitest.config.ts),
+ * so this sits next to the tests that need it without being run as one.
+ *
+ * macOS/Linux: plain `bash` off PATH, exactly as before.
+ *
+ * Windows: a bare `bash` is NOT usable and this is the whole reason the file
+ * exists. On a stock Windows 10/11, PATH resolves `bash` to
+ * `%LOCALAPPDATA%\Microsoft\WindowsApps\bash.exe` — the WSL app-execution-alias
+ * stub, a zero-length reparse point, not a shell. `existsSync` says yes and
+ * `where bash` prints it, but with no WSL distro registered CreateProcess
+ * refuses it outright ("Das System kann auf die Datei nicht zugreifen",
+ * ApplicationFailedException / NativeCommandFailed), so every
+ * execFileSync('bash', ...) dies before a shell is ever reached — which is what
+ * used to redden this file's tests on Windows while the code under test was
+ * fine. Git for Windows always installs a real bash alongside git, so resolve
+ * that deterministically and drop every WindowsApps candidate on the floor.
+ */
+import { execFileSync } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+
+const BASH_EXE = 'bash.exe'
+
+/** `...\WindowsApps\bash.exe` is the WSL alias stub — never an actual shell. */
+function isWslAliasStub(candidate: string): boolean {
+ return /[\\/]WindowsApps[\\/]/i.test(candidate)
+}
+
+/** `where` on Windows, one absolute path per line; missing program = no lines. */
+function whereOnPath(program: string): string[] {
+ try {
+ const out = execFileSync('where', [program], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ })
+ return out.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
+ } catch {
+ return []
+ }
+}
+
+/**
+ * Every place a real bash could be, most trustworthy first. Nothing here is
+ * machine-specific: git's own location is the primary source, the install
+ * roots are only the fallback for a git that is not on PATH.
+ */
+function windowsCandidates(): string[] {
+ const seen: string[] = []
+ const add = (candidate: string) => {
+ if (!seen.includes(candidate)) seen.push(candidate)
+ }
+
+ // 1. Derive it from git. Git for Windows ships bash in the same install, so
+ // `where git` -> ...\Git\cmd\git.exe pins down ...\Git\bin\bash.exe. Walk
+ // up a few levels instead of assuming `cmd\`, because git.exe also lives
+ // under mingw64\bin in some layouts.
+ for (const gitExe of whereOnPath('git')) {
+ let dir = dirname(gitExe)
+ for (let up = 0; up < 3; up++) {
+ dir = dirname(dir)
+ add(join(dir, 'bin', BASH_EXE))
+ add(join(dir, 'usr', 'bin', BASH_EXE))
+ }
+ }
+
+ // 2. The documented install roots, for a git that is not on PATH at all.
+ const localPrograms = process.env.LOCALAPPDATA
+ ? join(process.env.LOCALAPPDATA, 'Programs')
+ : undefined
+ for (const root of [
+ process.env.ProgramW6432,
+ process.env.ProgramFiles,
+ process.env['ProgramFiles(x86)'],
+ localPrograms,
+ ]) {
+ if (!root) continue
+ add(join(root, 'Git', 'bin', BASH_EXE))
+ add(join(root, 'Git', 'usr', 'bin', BASH_EXE))
+ }
+
+ // 3. Whatever PATH itself offers, last — and only after the stub filter, so
+ // a WSL alias can never win just because it happens to be first on PATH.
+ for (const onPath of whereOnPath('bash')) add(onPath)
+
+ return seen
+}
+
+let resolved: string | undefined
+
+/** The bash to spawn. Throws on Windows if no real one is installed. */
+export function bashInterpreter(): string {
+ if (resolved !== undefined) return resolved
+ if (process.platform !== 'win32') {
+ resolved = 'bash'
+ return resolved
+ }
+
+ const candidates = windowsCandidates()
+ const usable = candidates.find((c) => !isWslAliasStub(c) && existsSync(c))
+ if (!usable) {
+ throw new Error(
+ 'no usable bash found on Windows. The `bash` on PATH is the WSL ' +
+ 'app-execution-alias stub under WindowsApps, which cannot run without ' +
+ 'a registered WSL distro, so it is deliberately ignored. Install Git ' +
+ 'for Windows (https://git-scm.com/download/win, or `winget install ' +
+ '--id Git.Git`), which ships Git Bash. Checked:\n' +
+ candidates.map((c) => ` ${c}${isWslAliasStub(c) ? ' (WSL stub, skipped)' : ''}`).join('\n'),
+ )
+ }
+ resolved = usable
+ return resolved
+}
diff --git a/src/api/__tests__/build-llama-script.test.ts b/src/api/__tests__/build-llama-script.test.ts
index bfa1fa2e..1f4c12fc 100644
--- a/src/api/__tests__/build-llama-script.test.ts
+++ b/src/api/__tests__/build-llama-script.test.ts
@@ -3,11 +3,15 @@ import { execFileSync } from 'node:child_process'
import { resolve, join } from 'node:path'
import { existsSync, statSync, mkdtempSync, rmSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
+import { bashInterpreter } from './bash-interpreter'
// P0: unit-test the pure functions of scripts/build-llama.sh by sourcing it
// (main() is guarded so sourcing does not build anything) and invoking helpers.
const SCRIPT = resolve(__dirname, '../../../scripts/build-llama.sh')
const REPO_ROOT = resolve(__dirname, '../../..')
+// Not the bare name 'bash': on Windows that resolves to the WSL alias stub in
+// WindowsApps and never reaches a shell. See bash-interpreter.ts.
+const BASH = bashInterpreter()
/** Run a snippet with the script sourced. Returns stdout+stderr, both wanted:
* the pin guards report through die(), which writes to stderr. */
@@ -16,7 +20,7 @@ function runScript(
env: NodeJS.ProcessEnv = {},
): { code: number; out: string } {
try {
- const out = execFileSync('bash', ['-c', `source '${SCRIPT}'; ${snippet}`], {
+ const out = execFileSync(BASH, ['-c', `source '${SCRIPT}'; ${snippet}`], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, ...env },
@@ -32,7 +36,7 @@ function callFn(fn: string, ...args: string[]): { code: number; out: string } {
const argv = args.map((a) => `'${a}'`).join(' ')
try {
const out = execFileSync(
- 'bash',
+ BASH,
['-c', `source '${SCRIPT}'; ${fn} ${argv}`],
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
)
@@ -221,6 +225,51 @@ describe('build-llama.sh — the llama.cpp revision is pinned to a commit', () =
expect(second.out).toContain(`checkout is at ${up.sha}`)
})
+ it('refuses a checkout whose FILES changed under the pinned SHA', () => {
+ // The gap the SHA check alone leaves: `git rev-parse HEAD` proves where
+ // HEAD POINTS. cmake does not compile HEAD, it compiles the working tree —
+ // and a restored CI cache is an archive produced by an earlier run, in
+ // which the sources can say anything while .git/HEAD still names the pin.
+ const up = fakeUpstream()
+ const cache = tmp('llama-cache-tampered-')
+ const env = {
+ LLAMA_BUILD_CACHE: cache,
+ LLAMA_REPO: up.path,
+ LLAMA_TAG: up.tag,
+ LLAMA_COMMIT: up.sha,
+ }
+ expect(runScript('ensure_src', env).code).toBe(0)
+
+ writeFileSync(
+ join(cache, 'llama.cpp', 'CMakeLists.txt'),
+ 'project(fake)\nadd_definitions(-DBACKDOOR)\n',
+ )
+ const tampered = runScript('ensure_src', env)
+ expect(tampered.code, 'a modified source tree was accepted').not.toBe(0)
+ expect(tampered.out).toContain('does not match')
+ // HEAD is still exactly the pin, so the SHA check cannot be what caught it.
+ expect(git(join(cache, 'llama.cpp'), 'rev-parse', 'HEAD')).toBe(up.sha)
+ })
+
+ it('refuses an extra file smuggled into the checkout', () => {
+ // A tampered cache does not have to EDIT anything: llama.cpp pulls in
+ // whatever its CMake glob finds, so dropping a new file in is enough.
+ const up = fakeUpstream()
+ const cache = tmp('llama-cache-extra-')
+ const env = {
+ LLAMA_BUILD_CACHE: cache,
+ LLAMA_REPO: up.path,
+ LLAMA_TAG: up.tag,
+ LLAMA_COMMIT: up.sha,
+ }
+ expect(runScript('ensure_src', env).code).toBe(0)
+
+ writeFileSync(join(cache, 'llama.cpp', 'extra.cmake'), '# not in the pinned commit\n')
+ const extra = runScript('ensure_src', env)
+ expect(extra.code, 'an untracked file in the source tree was accepted').not.toBe(0)
+ expect(extra.out).toContain('extra.cmake')
+ })
+
it('hashes a digest of the binary it installed', () => {
const probe = join(tmp('llama-digest-'), 'artifact')
writeFileSync(probe, 'llama-server')