Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-9803 Fix Git probe timeout classification (#7284)

Nick Gomezfccbafe680ef
diff --git a/.changeset/git-probe-timeout.md b/.changeset/git-probe-timeout.md
new file mode 100644
index 000000000..acdca6c43
--- /dev/null
+++ b/.changeset/git-probe-timeout.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Keep Git probe timeouts separate from missing Git so installed Git is not reported as absent.
diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.ts
index b572e0ac1..a69fb4de3 100644
--- a/packages/cli/src/commands/clone.ts
+++ b/packages/cli/src/commands/clone.ts
@@ -16,6 +16,7 @@ import {
type CredentialUrlMatchReader,
type GitHubAccountSource,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
loginShapedUserinfoUser,
redactShareSubprocessStderr,
@@ -586,7 +587,11 @@ export function cloneCommand(getConfig: () => Config): Command {
await startCmd.parseAsync([], { from: 'user' });
}
} catch (err) {
- if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ if (
+ err instanceof GitNotAvailableError ||
+ err instanceof GitProbeTimeoutError ||
+ err instanceof GitTooOldError
+ ) {
if (opts.json) {
emit(true, { type: 'error', message: err.message });
} else {
diff --git a/packages/cli/src/commands/diagnose-health-checks/git.test.ts b/packages/cli/src/commands/diagnose-health-checks/git.test.ts
index 2b7922f4d..95699e2fe 100644
--- a/packages/cli/src/commands/diagnose-health-checks/git.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/git.test.ts
@@ -1,6 +1,7 @@
import {
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
type InstallGuidance,
} from '@inkeep/open-knowledge-server';
@@ -57,6 +58,19 @@ describe('git check', () => {
expect(result.detail).toContain('OpenKnowledge needs Git');
});
+ test('fails distinctly when the Git probe times out', async () => {
+ const def = makeGitCheck({
+ assert: () => {
+ throw new GitProbeTimeoutError('linux', guidance, { path: 'timeout', fallback: null });
+ },
+ });
+ const result = await def.run(ctx);
+ expect(result.status).toBe('fail');
+ expect(result.summary).toBe('git probe timed out');
+ expect(result.remediation).toContain('retry');
+ expect(result.detail).toContain('could not verify Git');
+ });
+
test('fails when assert throws GitTooOldError; surfaces detected + required', async () => {
const def = makeGitCheck({
assert: () => {
diff --git a/packages/cli/src/commands/diagnose-health-checks/git.ts b/packages/cli/src/commands/diagnose-health-checks/git.ts
index 6d9af19db..693ef8d6b 100644
--- a/packages/cli/src/commands/diagnose-health-checks/git.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/git.ts
@@ -3,6 +3,7 @@ import {
compareSemver,
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
MIN_GIT_VERSION,
SYMLINK_MERGE_MIN_GIT_LABEL,
@@ -32,6 +33,15 @@ export function makeGitCheck(deps: GitCheckDeps = {}): CheckDefinition {
}
return { name: 'git', status: 'pass', summary };
} catch (err) {
+ if (err instanceof GitProbeTimeoutError) {
+ return {
+ name: 'git',
+ status: 'fail',
+ summary: 'git probe timed out',
+ remediation: 'Check that Git is installed and retry',
+ detail: err.message,
+ };
+ }
if (err instanceof GitNotAvailableError) {
return {
name: 'git',
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 76b322837..4cb834b55 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -26,6 +26,7 @@ import {
ensureProjectGit,
FilesystemRootProjectError,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
HomeProjectRootError,
initContent,
@@ -2046,7 +2047,11 @@ export function initCommand(): Command {
process.exitCode = 64;
return;
}
- if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ if (
+ err instanceof GitNotAvailableError ||
+ err instanceof GitProbeTimeoutError ||
+ err instanceof GitTooOldError
+ ) {
process.stderr.write(`${err.message}\n`);
process.exitCode = 78;
return;
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 130183893..dfc56d597 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -728,6 +728,7 @@ export async function runStartCommand(configArg: Config, opts: StartCommandOptio
const serverModule = await import('@inkeep/open-knowledge-server');
if (
err instanceof serverModule.GitNotAvailableError ||
+ err instanceof serverModule.GitProbeTimeoutError ||
err instanceof serverModule.GitTooOldError
) {
process.exit(78);
diff --git a/packages/desktop/src/main/git-preflight-handler.test.ts b/packages/desktop/src/main/git-preflight-handler.test.ts
index 410204646..aa6cc1825 100644
--- a/packages/desktop/src/main/git-preflight-handler.test.ts
+++ b/packages/desktop/src/main/git-preflight-handler.test.ts
@@ -1,5 +1,6 @@
import {
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
type InstallGuidance,
} from '@inkeep/open-knowledge-server';
@@ -46,6 +47,30 @@ function showMessageBoxSequence(responses: readonly number[]) {
return { fn, calls };
}
+const WINDOWS_GUIDANCE: InstallGuidance = {
+ product: 'Git for Windows',
+ url: 'https://gitforwindows.org/',
+ options: [],
+};
+
+function probeTimeout(): GitProbeTimeoutError {
+ return new GitProbeTimeoutError('win32', WINDOWS_GUIDANCE, {
+ path: 'timeout',
+ fallback: 'timeout',
+ });
+}
+
+function showMessageBoxChoosing(chooseLabel: (opts: MessageBoxOptions, call: number) => string) {
+ const calls: MessageBoxOptions[] = [];
+ const fn = vi.fn(async (opts: MessageBoxOptions) => {
+ calls.push(opts);
+ const label = chooseLabel(opts, calls.length);
+ expect(opts.buttons, `buttons of dialog #${calls.length}`).toContain(label);
+ return { response: opts.buttons.indexOf(label) };
+ });
+ return { fn, calls };
+}
+
describe('ensureGitAvailable', () => {
test("returns 'ok' on first-try success without showing dialog", async () => {
const assertGitAvailable = vi.fn(() => ({
@@ -187,6 +212,213 @@ describe('ensureGitAvailable', () => {
expect(boxCalls[0]?.detail).toContain('detected 2.20.0 at /usr/bin/git');
});
+ test('GitProbeTimeoutError uses timeout guidance instead of Git-not-found guidance', async () => {
+ const assertGitAvailable = vi.fn(() => {
+ throw new GitProbeTimeoutError(
+ 'win32',
+ {
+ product: 'Git for Windows',
+ url: 'https://gitforwindows.org/',
+ options: [],
+ },
+ { path: 'timeout', fallback: 'timeout' },
+ );
+ });
+ const { fn: showMessageBox, calls: boxCalls } = showMessageBoxChoosing(() => 'Quit');
+ const outcome = await ensureGitAvailable({
+ assertGitAvailable,
+ showMessageBox,
+ openExternal: vi.fn(async () => {}),
+ });
+
+ expect(outcome).toBe('aborted');
+ expect(boxCalls[0]?.title).toBe('Git probe timed out');
+ expect(boxCalls[0]?.message).toContain('could not verify Git for Windows');
+ expect(boxCalls[0]?.message).not.toContain('Git not found');
+ const buttons = boxCalls[0]?.buttons ?? [];
+ expect(buttons).toEqual(['Retry', 'Quit']);
+ expect(buttons[boxCalls[0]?.defaultId ?? -1]).toBe('Retry');
+ expect(buttons[boxCalls[0]?.cancelId ?? -1]).toBe('Quit');
+ });
+
+ test('no button on a probe-timeout dialog opens the install page', async () => {
+ const discovery = showMessageBoxChoosing(() => 'Quit');
+ await ensureGitAvailable({
+ assertGitAvailable: vi.fn(() => {
+ throw probeTimeout();
+ }),
+ showMessageBox: discovery.fn,
+ openExternal: vi.fn(async () => {}),
+ });
+ const timeoutButtons = discovery.calls[0]?.buttons ?? [];
+ expect(timeoutButtons.length).toBeGreaterThan(0);
+
+ for (const [index, label] of timeoutButtons.entries()) {
+ const openExternal = vi.fn(async (_url: string) => {});
+ const answers: number[] = [];
+ const showMessageBox = vi.fn(async (opts: MessageBoxOptions) => {
+ const response = answers.length === 0 ? index : opts.buttons.indexOf('Quit');
+ answers.push(response);
+ return { response };
+ });
+
+ const outcome = await ensureGitAvailable({
+ assertGitAvailable: vi.fn(() => {
+ throw probeTimeout();
+ }),
+ showMessageBox,
+ openExternal,
+ });
+
+ expect(outcome, `pressing ${label}`).toBe('aborted');
+ expect(openExternal, `pressing ${label}`).not.toHaveBeenCalled();
+ }
+ });
+
+ test('Retry on a probe-timeout dialog re-runs the probe and logs a retry', async () => {
+ let attempts = 0;
+ const assertGitAvailable = vi.fn(() => {
+ attempts += 1;
+ if (attempts === 1) {
+ throw probeTimeout();
+ }
+ return {
+ ok: true as const,
+ version: '2.56.0',
+ resolvedPath: 'C:\\Program Files\\Git\\cmd\\git.exe',
+ source: 'PATH' as const,
+ };
+ });
+ const { fn: showMessageBox, calls: boxCalls } = showMessageBoxChoosing(() => 'Retry');
+ const openExternal = vi.fn(async (_url: string) => {});
+ const info = vi.fn((_msg: string, _obj?: unknown) => {});
+
+ const outcome = await ensureGitAvailable({
+ assertGitAvailable,
+ showMessageBox,
+ openExternal,
+ log: { warn: vi.fn(), info },
+ });
+
+ expect(outcome).toBe('recovered');
+ expect(attempts).toBe(2);
+ expect(boxCalls).toHaveLength(1);
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(info).toHaveBeenCalledTimes(1);
+ expect(info.mock.calls[0]?.[1]).toEqual({ response: 'retry' });
+ });
+
+ test('a response outside the probe-timeout button set aborts as unexpected', async () => {
+ const discovery = showMessageBoxChoosing(() => 'Quit');
+ await ensureGitAvailable({
+ assertGitAvailable: vi.fn(() => {
+ throw probeTimeout();
+ }),
+ showMessageBox: discovery.fn,
+ openExternal: vi.fn(async () => {}),
+ });
+ const outOfRange = discovery.calls[0]?.buttons.length ?? 0;
+ expect(outOfRange).toBeGreaterThan(0);
+
+ const assertGitAvailable = vi.fn(() => {
+ throw probeTimeout();
+ });
+ const openExternal = vi.fn(async (_url: string) => {});
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
+
+ const outcome = await ensureGitAvailable({
+ assertGitAvailable,
+ showMessageBox: vi.fn(async () => ({ response: outOfRange })),
+ openExternal,
+ log: { warn },
+ });
+
+ expect(outcome).toBe('aborted');
+ expect(assertGitAvailable).toHaveBeenCalledTimes(1);
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(warn.mock.calls.at(-1)?.[0]).toContain('unexpected dialog response');
+ expect(warn.mock.calls.at(-1)?.[1]).toEqual({ response: outOfRange });
+ });
+
+ test('a probe timeout after a failed install-page open omits the browser fallback note', async () => {
+ let attempts = 0;
+ const assertGitAvailable = vi.fn(() => {
+ attempts += 1;
+ if (attempts === 1) {
+ throw new GitNotAvailableError('darwin', MAC_GUIDANCE);
+ }
+ throw probeTimeout();
+ });
+ const { fn: showMessageBox, calls: boxCalls } = showMessageBoxChoosing((_opts, call) => {
+ if (call === 1) return 'Open Install Page';
+ if (call === 2) return "I've Installed Git — Retry";
+ return 'Quit';
+ });
+ const openExternal = vi.fn(async (_url: string) => {
+ throw new Error('no default browser configured');
+ });
+
+ const outcome = await ensureGitAvailable({
+ assertGitAvailable,
+ showMessageBox,
+ openExternal,
+ log: { warn: vi.fn() },
+ });
+
+ expect(outcome).toBe('aborted');
+ expect(boxCalls).toHaveLength(3);
+ expect(boxCalls[1]?.title).toBe('Git not found');
+ expect(boxCalls[1]?.detail).toContain('Could not open browser automatically');
+ expect(boxCalls[2]?.title).toBe('Git probe timed out');
+ expect(boxCalls[2]?.detail).not.toContain('Could not open browser');
+ expect(boxCalls[2]?.detail).not.toContain(MAC_GUIDANCE.url);
+ });
+
+ test('a probe timeout logs its probe results without install wording', async () => {
+ const { fn: showMessageBox } = showMessageBoxChoosing(() => 'Quit');
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
+
+ await ensureGitAvailable({
+ assertGitAvailable: vi.fn(() => {
+ throw probeTimeout();
+ }),
+ showMessageBox,
+ openExternal: vi.fn(async () => {}),
+ log: { warn },
+ });
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ const [message, fields] = warn.mock.calls[0] ?? [];
+ expect(fields).toEqual({
+ code: 'GIT_PROBE_TIMEOUT',
+ platform: 'win32',
+ pathProbe: 'timeout',
+ fallbackProbe: 'timeout',
+ });
+ expect(message).not.toMatch(/git unavailable/i);
+ expect(message).not.toMatch(/install dialog/i);
+ });
+
+ test('a too-old Git keeps the install-page, installed-retry and quit buttons', async () => {
+ const { fn: showMessageBox, calls: boxCalls } = showMessageBoxChoosing(() => 'Quit');
+
+ await ensureGitAvailable({
+ assertGitAvailable: vi.fn(() => {
+ throw new GitTooOldError('linux', '2.20.0', '2.31.0', '/usr/bin/git', LINUX_GUIDANCE);
+ }),
+ showMessageBox,
+ openExternal: vi.fn(async () => {}),
+ });
+
+ expect(boxCalls[0]?.buttons).toEqual([
+ 'Open Install Page',
+ "I've Installed Git — Retry",
+ 'Quit',
+ ]);
+ expect(boxCalls[0]?.defaultId).toBe(1);
+ expect(boxCalls[0]?.cancelId).toBe(2);
+ });
+
test("non-typed error from preflight shows error dialog before 'aborted'", async () => {
const assertGitAvailable = vi.fn(() => {
throw new Error('something completely different');
diff --git a/packages/desktop/src/main/git-preflight-handler.ts b/packages/desktop/src/main/git-preflight-handler.ts
index 09f78b595..1fbf08f7f 100644
--- a/packages/desktop/src/main/git-preflight-handler.ts
+++ b/packages/desktop/src/main/git-preflight-handler.ts
@@ -2,6 +2,7 @@ import {
emitPreflightFailureSpan,
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
} from '@inkeep/open-knowledge-server';
@@ -31,19 +32,59 @@ export interface EnsureGitDeps {
};
}
-const BUTTON_OPEN_INSTALL_PAGE = 0;
-const BUTTON_RETRY = 1;
-const BUTTON_QUIT = 2;
+type DialogAction = 'open-install-page' | 'retry' | 'quit';
-const BUTTON_LABELS = ['Open Install Page', "I've Installed Git — Retry", 'Quit'] as const;
+interface DialogButton {
+ readonly action: DialogAction;
+ readonly label: string;
+}
+
+const INSTALL_BUTTONS = [
+ { action: 'open-install-page', label: 'Open Install Page' },
+ { action: 'retry', label: "I've Installed Git — Retry" },
+ { action: 'quit', label: 'Quit' },
+] as const satisfies readonly DialogButton[];
+
+const PROBE_TIMEOUT_BUTTONS = [
+ { action: 'retry', label: 'Retry' },
+ { action: 'quit', label: 'Quit' },
+] as const satisfies readonly DialogButton[];
+
+interface PreflightDialog {
+ readonly title: string;
+ readonly message: string;
+ readonly waitingLog: string;
+ readonly buttons: readonly DialogButton[];
+}
-const BUTTON_NAMES: Readonly<Partial<Record<number, string>>> = {
- [BUTTON_OPEN_INSTALL_PAGE]: 'open-install-page',
- [BUTTON_RETRY]: 'retry',
- [BUTTON_QUIT]: 'quit',
-};
+function preflightDialog(
+ err: GitNotAvailableError | GitProbeTimeoutError | GitTooOldError,
+): PreflightDialog {
+ if (err instanceof GitProbeTimeoutError) {
+ return {
+ title: 'Git probe timed out',
+ message: `OpenKnowledge could not verify ${err.guidance.product} because the Git probe timed out.`,
+ waitingLog: 'ensureGitAvailable: git probe timed out, startup is waiting on the retry dialog',
+ buttons: PROBE_TIMEOUT_BUTTONS,
+ };
+ }
+ if (err instanceof GitTooOldError) {
+ return {
+ title: 'Git too old',
+ message: `OpenKnowledge requires ${err.guidance.product} ${err.required} or newer.`,
+ waitingLog: 'ensureGitAvailable: git unavailable, startup is waiting on the install dialog',
+ buttons: INSTALL_BUTTONS,
+ };
+ }
+ return {
+ title: 'Git not found',
+ message: `OpenKnowledge needs ${err.guidance.product} to track changes to your knowledge base.`,
+ waitingLog: 'ensureGitAvailable: git unavailable, startup is waiting on the install dialog',
+ buttons: INSTALL_BUTTONS,
+ };
+}
-function preflightFailureFields(err: GitNotAvailableError | GitTooOldError) {
+function preflightFailureFields(err: GitNotAvailableError | GitProbeTimeoutError | GitTooOldError) {
if (err instanceof GitTooOldError) {
return {
code: err.code,
@@ -53,6 +94,14 @@ function preflightFailureFields(err: GitNotAvailableError | GitTooOldError) {
resolvedPath: err.resolvedPath,
};
}
+ if (err instanceof GitProbeTimeoutError) {
+ return {
+ code: err.code,
+ platform: err.platform,
+ pathProbe: err.probe.path,
+ fallbackProbe: err.probe.fallback,
+ };
+ }
return {
code: err.code,
platform: err.platform,
@@ -63,7 +112,7 @@ function preflightFailureFields(err: GitNotAvailableError | GitTooOldError) {
type PreflightAttempt =
| { kind: 'ok'; detection: GitDetected }
- | { kind: 'typed'; err: GitNotAvailableError | GitTooOldError }
+ | { kind: 'typed'; err: GitNotAvailableError | GitProbeTimeoutError | GitTooOldError }
| { kind: 'unknown'; err: Error };
async function showUnknownErrorDialog(deps: EnsureGitDeps, err: Error): Promise<void> {
@@ -88,7 +137,11 @@ function tryPreflight(fn: () => GitDetected): PreflightAttempt {
try {
return { kind: 'ok', detection: fn() };
} catch (err) {
- if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ if (
+ err instanceof GitNotAvailableError ||
+ err instanceof GitProbeTimeoutError ||
+ err instanceof GitTooOldError
+ ) {
return { kind: 'typed', err };
}
return { kind: 'unknown', err: err instanceof Error ? err : new Error(String(err)) };
@@ -110,33 +163,30 @@ export async function ensureGitAvailable(deps: EnsureGitDeps): Promise<EnsureGit
let currentErr = first.err;
let failedInstallUrl: string | null = null;
while (true) {
- const title = currentErr instanceof GitTooOldError ? 'Git too old' : 'Git not found';
- const message =
- currentErr instanceof GitTooOldError
- ? `OpenKnowledge requires ${currentErr.guidance.product} ${currentErr.required} or newer.`
- : `OpenKnowledge needs ${currentErr.guidance.product} to track changes to your knowledge base.`;
+ const dialog = preflightDialog(currentErr);
+ const offersInstallPage = dialog.buttons.some(
+ (button) => button.action === 'open-install-page',
+ );
const detail =
- failedInstallUrl === null
+ failedInstallUrl === null || !offersInstallPage
? currentErr.message
: `${currentErr.message}\n\nCould not open browser automatically. Please visit: ${failedInstallUrl}`;
- deps.log?.warn(
- 'ensureGitAvailable: git unavailable, startup is waiting on the install dialog',
- preflightFailureFields(currentErr),
- );
+ deps.log?.warn(dialog.waitingLog, preflightFailureFields(currentErr));
const result = await deps.showMessageBox({
type: 'warning',
- buttons: BUTTON_LABELS,
- defaultId: BUTTON_RETRY,
- cancelId: BUTTON_QUIT,
- title,
- message,
+ buttons: dialog.buttons.map((button) => button.label),
+ defaultId: dialog.buttons.findIndex((button) => button.action === 'retry'),
+ cancelId: dialog.buttons.findIndex((button) => button.action === 'quit'),
+ title: dialog.title,
+ message: dialog.message,
detail,
});
+ const action = dialog.buttons[result.response]?.action;
deps.log?.info?.('ensureGitAvailable: install dialog answered', {
- response: BUTTON_NAMES[result.response] ?? result.response,
+ response: action ?? result.response,
});
- if (result.response === BUTTON_OPEN_INSTALL_PAGE) {
+ if (action === 'open-install-page') {
try {
await deps.openExternal(currentErr.guidance.url);
failedInstallUrl = null;
@@ -150,7 +200,7 @@ export async function ensureGitAvailable(deps: EnsureGitDeps): Promise<EnsureGit
continue;
}
- if (result.response === BUTTON_RETRY) {
+ if (action === 'retry') {
const retry = tryPreflight(deps.assertGitAvailable);
if (retry.kind === 'ok') return 'recovered';
if (retry.kind === 'typed') {
@@ -165,7 +215,7 @@ export async function ensureGitAvailable(deps: EnsureGitDeps): Promise<EnsureGit
return 'aborted';
}
- if (result.response === BUTTON_QUIT) {
+ if (action === 'quit') {
return 'aborted';
}
diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.ts
index abb023e14..5a47da0b9 100644
--- a/packages/desktop/src/utility/server-entry.ts
+++ b/packages/desktop/src/utility/server-entry.ts
@@ -333,7 +333,9 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {
errMsg.kind = 'authority-registry';
}
const isGitPreflightFailure =
- errName === 'GitNotAvailableError' || errName === 'GitTooOldError';
+ errName === 'GitNotAvailableError' ||
+ errName === 'GitProbeTimeoutError' ||
+ errName === 'GitTooOldError';
deps.parentPort?.postMessage(errMsg);
rejectReady(err as Error);
deps.exit(isGitPreflightFailure ? 78 : 1);
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 39a77051d..c71c9b887 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -38,9 +38,13 @@ import {
assertGitAvailable,
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
} from './git-preflight.ts';
-import { emitPreflightFailureSpan } from './git-preflight-telemetry.ts';
+import {
+ describeGitPreflightFailure,
+ emitPreflightFailureSpan,
+} from './git-preflight-telemetry.ts';
import { createShellHeaderSetter } from './http/shell-csp.ts';
import {
attachCollabClientCounter,
@@ -349,18 +353,21 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
try {
if (opts.gitEnabled !== false) preflight();
} catch (err) {
- if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
- const detectedVersion = err instanceof GitTooOldError ? err.detected : '';
- const reason = err instanceof GitTooOldError ? 'too_old' : 'not_available';
+ if (
+ err instanceof GitNotAvailableError ||
+ err instanceof GitProbeTimeoutError ||
+ err instanceof GitTooOldError
+ ) {
+ const failure = describeGitPreflightFailure(err);
emitPreflightFailureSpan(err);
log.warn(
{
event: 'git_preflight_fail',
platform: err.platform,
- reason,
- detectedVersion,
+ reason: failure.reason,
+ detectedVersion: failure.detectedVersion,
},
- reason === 'not_available' ? 'git binary not found' : 'git binary too old',
+ failure.logMessage,
);
process.stderr.write(`${err.message}\n`);
}
diff --git a/packages/server/src/git-preflight-boot.test.ts b/packages/server/src/git-preflight-boot.test.ts
index 14f878ac8..05bfa0b3c 100644
--- a/packages/server/src/git-preflight-boot.test.ts
+++ b/packages/server/src/git-preflight-boot.test.ts
@@ -15,6 +15,7 @@ import { ConfigSchema } from './config/schema.ts';
import {
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
type InstallGuidance,
} from './git-preflight.ts';
@@ -178,6 +179,59 @@ describe('bootServer git-preflight', () => {
expect(entry?.msg).toBe('git binary too old');
});
+ test('GitProbeTimeoutError → structured log carries reason=probe_timeout + empty detectedVersion', async () => {
+ const projectDir = await mkdtemp(resolve(tmpDir, 'state-'));
+ seedOkScaffold(projectDir);
+
+ const { entries, logger } = createCaptureLogger();
+
+ let capturedStderr = '';
+ const originalStderrWrite = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: unknown) => {
+ capturedStderr += String(chunk);
+ return true;
+ }) as never;
+
+ const thrown = new GitProbeTimeoutError('win32', makeGuidance(), {
+ path: 'timeout',
+ fallback: 'timeout',
+ });
+
+ let caught: unknown;
+ try {
+ await bootServer({
+ config: TEST_CONFIG,
+ contentDir: projectDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: true,
+ idleShutdownMs: null,
+ log: logger,
+ gitPreflight: () => {
+ throw thrown;
+ },
+ });
+ } catch (err) {
+ caught = err;
+ } finally {
+ process.stderr.write = originalStderrWrite;
+ }
+
+ expect(caught).toBe(thrown);
+ expect(caught).toBeInstanceOf(GitProbeTimeoutError);
+
+ expect(capturedStderr).toContain('the Git probe timed out');
+ expect(capturedStderr).toContain('PATH=timeout, fallback=timeout');
+
+ expect(entries).toHaveLength(1);
+ const [entry] = entries;
+ expect(entry?.fields.event).toBe('git_preflight_fail');
+ expect(entry?.fields.platform).toBe('win32');
+ expect(entry?.fields.reason).toBe('probe_timeout');
+ expect(entry?.fields.detectedVersion).toBe('');
+ expect(entry?.msg).toBe('git probe timed out');
+ });
+
test('non-typed error from preflight propagates unchanged — no log, no stderr', async () => {
const projectDir = await mkdtemp(resolve(tmpDir, 'state-'));
seedOkScaffold(projectDir);
diff --git a/packages/server/src/git-preflight-probe-spawn.test.ts b/packages/server/src/git-preflight-probe-spawn.test.ts
index 991ba369c..a45b57b86 100644
--- a/packages/server/src/git-preflight-probe-spawn.test.ts
+++ b/packages/server/src/git-preflight-probe-spawn.test.ts
@@ -14,7 +14,9 @@ vi.mock('node:fs', async (importOriginal) => {
return { ...actual, existsSync: existsSyncMock };
});
-const { detectGit, fallbackPaths, GitNotAvailableError } = await import('./git-preflight.ts');
+const { detectGit, fallbackPaths, GitNotAvailableError, GitProbeTimeoutError } = await import(
+ './git-preflight.ts'
+);
function spawnError(code: string): SpawnSyncReturns<string> {
const error = Object.assign(new Error(`spawnSync git ${code}`), { code });
@@ -25,6 +27,11 @@ function exited(status: number, stdout: string): SpawnSyncReturns<string> {
return { pid: 1, output: [], stdout, stderr: '', status, signal: null };
}
+function timedOut(): SpawnSyncReturns<string> {
+ const error = Object.assign(new Error('spawnSync git ETIMEDOUT'), { code: 'ETIMEDOUT' });
+ return { pid: 1, output: [], stdout: '', stderr: '', status: null, signal: 'SIGTERM', error };
+}
+
function probeOf(fn: () => unknown) {
try {
fn();
@@ -47,6 +54,61 @@ describe('detectGit probe reasons with a stubbed spawn', () => {
expect(probeOf(detectGit)).toEqual({ path: 'spawn-failed', fallback: null });
});
+ test('a timed-out git probe is not reported as GitNotAvailableError', () => {
+ spawnSyncMock.mockReturnValue(timedOut());
+ let thrown: unknown;
+ try {
+ detectGit();
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).not.toBeInstanceOf(GitNotAvailableError);
+ expect(thrown).toBeInstanceOf(GitProbeTimeoutError);
+ });
+
+ test('a timed-out fallback probe is not reported as GitNotAvailableError', (ctx) => {
+ const [candidate] = fallbackPaths(process.platform);
+ ctx.skip(candidate === undefined, 'this platform has no fallback git candidates');
+ existsSyncMock.mockImplementation((path: unknown) => path === candidate);
+ spawnSyncMock.mockImplementation((command: string) =>
+ command === 'git' ? spawnError('ENOENT') : timedOut(),
+ );
+ let thrown: unknown;
+ try {
+ detectGit();
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(GitProbeTimeoutError);
+ expect(thrown).not.toBeInstanceOf(GitNotAvailableError);
+ });
+
+ test('timeout evidence survives a later fallback failure', (ctx) => {
+ const candidates = fallbackPaths(process.platform);
+ const first = candidates[0];
+ const second = candidates[1];
+ ctx.skip(
+ first === undefined || second === undefined,
+ 'this platform has too few fallback candidates',
+ );
+ existsSyncMock.mockImplementation((path: unknown) => path === first || path === second);
+ spawnSyncMock.mockImplementation((command: string) => {
+ if (command === 'git') return spawnError('ENOENT');
+ return command === first ? timedOut() : exited(1, '');
+ });
+ let thrown: unknown;
+ try {
+ detectGit();
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(GitProbeTimeoutError);
+ expect((thrown as InstanceType<typeof GitProbeTimeoutError>).probe).toEqual({
+ path: 'enoent',
+ fallback: 'timeout',
+ });
+ });
+
test('a failing fallback candidate records its own reason', (ctx) => {
const [candidate] = fallbackPaths(process.platform);
ctx.skip(candidate === undefined, 'this platform has no fallback git candidates');
diff --git a/packages/server/src/git-preflight-spawn.test.ts b/packages/server/src/git-preflight-spawn.test.ts
index b4c55032e..ff3104f9e 100644
--- a/packages/server/src/git-preflight-spawn.test.ts
+++ b/packages/server/src/git-preflight-spawn.test.ts
@@ -165,4 +165,55 @@ describe('bootServer() preflight survives the subprocess boundary (FR6 / US-005)
await rm(projectDir, { recursive: true, force: true });
}
}, 30_000);
+
+ test('subprocess that throws GitProbeTimeoutError exits 78 with timeout guidance', async () => {
+ const projectDir = await mkdtemp(resolve(tmpdir(), 'ok-spawn-preflight-timeout-'));
+ try {
+ seedOkScaffold(projectDir);
+
+ const inlineDriver = `
+ const { bootServer } = await import('./src/boot.ts');
+ const { ConfigSchema } = await import('./src/config/schema.ts');
+ const { GitProbeTimeoutError } = await import('./src/git-preflight.ts');
+ const projectDir = process.env.OK_TEST_PROJECT_DIR;
+ const guidance = { product: 'Git for Windows', url: 'https://gitforwindows.org/', options: [] };
+ try {
+ await bootServer({
+ config: ConfigSchema.parse({}),
+ contentDir: projectDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: true,
+ idleShutdownMs: null,
+ gitPreflight: () => {
+ throw new GitProbeTimeoutError('win32', guidance, { path: 'timeout', fallback: null });
+ },
+ });
+ } catch (err) {
+ if (err instanceof GitProbeTimeoutError) process.exit(78);
+ console.error('UNEXPECTED-CATCH: ' + (err && err.message));
+ process.exit(97);
+ }
+ process.exit(96);
+ `;
+
+ const result = Bun.spawnSync({
+ cmd: ['node', '--import', 'tsx', '--conditions=development', '-e', inlineDriver],
+ cwd: SERVER_PACKAGE_ROOT,
+ env: {
+ ...process.env,
+ NO_COLOR: '1',
+ OK_TEST_PROJECT_DIR: projectDir,
+ OTEL_SDK_DISABLED: 'true',
+ },
+ });
+
+ const stderr = result.stderr.toString();
+ expect(result.exitCode).toBe(78);
+ expect(stderr).toContain('could not verify Git for Windows');
+ expect(stderr).not.toContain('UNEXPECTED-CATCH');
+ } finally {
+ await rm(projectDir, { recursive: true, force: true });
+ }
+ }, 30_000);
});
diff --git a/packages/server/src/git-preflight-telemetry.test.ts b/packages/server/src/git-preflight-telemetry.test.ts
index 4b9d570ff..dea8a7b9d 100644
--- a/packages/server/src/git-preflight-telemetry.test.ts
+++ b/packages/server/src/git-preflight-telemetry.test.ts
@@ -5,7 +5,12 @@ import {
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { GitNotAvailableError, GitTooOldError, type InstallGuidance } from './git-preflight.ts';
+import {
+ GitNotAvailableError,
+ GitProbeTimeoutError,
+ GitTooOldError,
+ type InstallGuidance,
+} from './git-preflight.ts';
import {
emitPreflightFailureSpan,
GIT_PREFLIGHT_FAIL_SPAN_NAME,
@@ -96,6 +101,21 @@ describe('emitPreflightFailureSpan — GitTooOldError', () => {
});
});
+describe('emitPreflightFailureSpan — GitProbeTimeoutError', () => {
+ test('emits reason=probe_timeout', () => {
+ const err = new GitProbeTimeoutError('win32', makeGuidance(), {
+ path: 'timeout',
+ fallback: 'timeout',
+ });
+ emitPreflightFailureSpan(err);
+
+ const [span] = exporter.getFinishedSpans();
+ expect(span?.attributes['ok.platform']).toBe('win32');
+ expect(span?.attributes['ok.preflight.git.reason']).toBe('probe_timeout');
+ expect(span?.attributes['ok.preflight.git.detected_version']).toBe('');
+ });
+});
+
describe('emitPreflightFailureSpan — cardinality discipline (FR8 AC8.5)', () => {
test('attribute set is exactly the three FR8-pinned keys', () => {
const err = new GitNotAvailableError('linux', makeGuidance());
diff --git a/packages/server/src/git-preflight-telemetry.ts b/packages/server/src/git-preflight-telemetry.ts
index 8ebe56d0f..aa5fe97ca 100644
--- a/packages/server/src/git-preflight-telemetry.ts
+++ b/packages/server/src/git-preflight-telemetry.ts
@@ -1,11 +1,45 @@
-import { type GitNotAvailableError, GitTooOldError } from './git-preflight.ts';
+import {
+ type GitNotAvailableError,
+ type GitProbeTimeoutError,
+ GitTooOldError,
+} from './git-preflight.ts';
import { withSpanSync } from './telemetry.ts';
export const GIT_PREFLIGHT_FAIL_SPAN_NAME = 'ok.preflight.git.fail';
-export function emitPreflightFailureSpan(err: GitNotAvailableError | GitTooOldError): void {
- const reason = err instanceof GitTooOldError ? 'too_old' : 'not_available';
- const detectedVersion = err instanceof GitTooOldError ? err.detected : '';
+export type GitPreflightError = GitNotAvailableError | GitProbeTimeoutError | GitTooOldError;
+
+const FAILURE_REASON_BY_CODE = {
+ GIT_NOT_AVAILABLE: 'not_available',
+ GIT_PROBE_TIMEOUT: 'probe_timeout',
+ GIT_TOO_OLD: 'too_old',
+} as const satisfies Record<GitPreflightError['code'], string>;
+
+type GitPreflightFailureReason = (typeof FAILURE_REASON_BY_CODE)[GitPreflightError['code']];
+
+const FAILURE_LOG_MESSAGE_BY_REASON = {
+ not_available: 'git binary not found',
+ probe_timeout: 'git probe timed out',
+ too_old: 'git binary too old',
+} as const satisfies Record<GitPreflightFailureReason, string>;
+
+export interface GitPreflightFailure {
+ readonly reason: GitPreflightFailureReason;
+ readonly detectedVersion: string;
+ readonly logMessage: (typeof FAILURE_LOG_MESSAGE_BY_REASON)[GitPreflightFailureReason];
+}
+
+export function describeGitPreflightFailure(err: GitPreflightError): GitPreflightFailure {
+ const reason = FAILURE_REASON_BY_CODE[err.code];
+ return {
+ reason,
+ detectedVersion: err instanceof GitTooOldError ? err.detected : '',
+ logMessage: FAILURE_LOG_MESSAGE_BY_REASON[reason],
+ };
+}
+
+export function emitPreflightFailureSpan(err: GitPreflightError): void {
+ const { reason, detectedVersion } = describeGitPreflightFailure(err);
withSpanSync(
GIT_PREFLIGHT_FAIL_SPAN_NAME,
{
diff --git a/packages/server/src/git-preflight.test.ts b/packages/server/src/git-preflight.test.ts
index 2ad52b30d..41a28c4b9 100644
--- a/packages/server/src/git-preflight.test.ts
+++ b/packages/server/src/git-preflight.test.ts
@@ -11,6 +11,7 @@ import {
fallbackPaths,
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
type InstallGuidance,
type LinuxFamily,
@@ -267,6 +268,20 @@ describe('GitNotAvailableError', () => {
});
});
+describe('GitProbeTimeoutError', () => {
+ test('carries a distinct code and avoids missing-Git guidance', () => {
+ const err = new GitProbeTimeoutError('win32', buildGuidance('win32'), {
+ path: 'timeout',
+ fallback: 'timeout',
+ });
+ expect(err.code).toBe('GIT_PROBE_TIMEOUT');
+ expect(err.name).toBe('GitProbeTimeoutError');
+ expect(err.probe).toEqual({ path: 'timeout', fallback: 'timeout' });
+ expect(err.message).toContain('could not verify Git for Windows');
+ expect(err.message).not.toContain("isn't installed");
+ });
+});
+
describe('GitTooOldError', () => {
test('carries code, platform, detected, required, and resolvedPath fields', () => {
const guidance = buildGuidance('darwin');
diff --git a/packages/server/src/git-preflight.ts b/packages/server/src/git-preflight.ts
index 617979043..55dde9054 100644
--- a/packages/server/src/git-preflight.ts
+++ b/packages/server/src/git-preflight.ts
@@ -54,6 +54,21 @@ export class GitNotAvailableError extends Error {
}
}
+export class GitProbeTimeoutError extends Error {
+ readonly code = 'GIT_PROBE_TIMEOUT';
+ readonly platform: NodeJS.Platform;
+ readonly guidance: InstallGuidance;
+ readonly probe: GitProbeFailures;
+
+ constructor(platform: NodeJS.Platform, guidance: InstallGuidance, probe: GitProbeFailures) {
+ super(buildProbeTimeoutMessage(guidance, probe));
+ this.name = 'GitProbeTimeoutError';
+ this.platform = platform;
+ this.guidance = guidance;
+ this.probe = probe;
+ }
+}
+
export class GitTooOldError extends Error {
readonly code = 'GIT_TOO_OLD';
readonly platform: NodeJS.Platform;
@@ -92,6 +107,7 @@ export function detectGit(): GitDetected {
}
let fallback: GitProbeFailureReason | null = null;
+ let fallbackTimedOut = false;
for (const candidate of fallbackPaths(process.platform)) {
if (!existsSync(candidate)) continue;
const result = probeGit(candidate);
@@ -104,11 +120,17 @@ export function detectGit(): GitDetected {
};
}
fallback = result.reason;
+ fallbackTimedOut ||= result.reason === 'timeout';
}
- throw new GitNotAvailableError(process.platform, buildGuidance(process.platform), {
- probe: { path: stage1.reason, fallback },
- });
+ const probe = {
+ path: stage1.reason,
+ fallback: fallbackTimedOut ? 'timeout' : fallback,
+ };
+ if (stage1.reason === 'timeout' || fallbackTimedOut) {
+ throw new GitProbeTimeoutError(process.platform, buildGuidance(process.platform), probe);
+ }
+ throw new GitNotAvailableError(process.platform, buildGuidance(process.platform), { probe });
}
export function assertGitAvailable(): GitDetected {
@@ -402,6 +424,16 @@ function buildMissingMessage(g: InstallGuidance): string {
return lines.join('\n');
}
+function buildProbeTimeoutMessage(g: InstallGuidance, probe: GitProbeFailures): string {
+ return [
+ `OpenKnowledge could not verify ${g.product} because the Git probe timed out. Git may be installed but unavailable while the machine is busy.`,
+ '',
+ `Probe results: PATH=${probe.path}, fallback=${probe.fallback ?? 'not attempted'}.`,
+ 'Check that Git is installed and retry OpenKnowledge.',
+ `Run \`${currentCliCommandName()} diagnose health --check git\` to verify your installation.`,
+ ].join('\n');
+}
+
function buildTooOldMessage(
detected: string,
required: string,
diff --git a/packages/server/src/git-unusable-setup.test-helper.ts b/packages/server/src/git-unusable-setup.test-helper.ts
index e219aefe5..224ae493d 100644
--- a/packages/server/src/git-unusable-setup.test-helper.ts
+++ b/packages/server/src/git-unusable-setup.test-helper.ts
@@ -62,12 +62,19 @@ export async function withUnusableGitEverywhere(fn: () => Promise<void>): Promis
export function isRecoverableGitSignal(value: unknown): boolean {
if (value == null) return false;
const code = (value as { code?: unknown }).code;
- if (code === 'GIT_NOT_AVAILABLE' || code === 'GIT_TOO_OLD') return true;
+ if (code === 'GIT_NOT_AVAILABLE' || code === 'GIT_PROBE_TIMEOUT' || code === 'GIT_TOO_OLD')
+ return true;
const name = (value as { name?: unknown }).name;
- if (name === 'GitNotAvailableError' || name === 'GitTooOldError') return true;
+ if (
+ name === 'GitNotAvailableError' ||
+ name === 'GitProbeTimeoutError' ||
+ name === 'GitTooOldError'
+ )
+ return true;
const msg = value instanceof Error ? value.message : typeof value === 'string' ? value : '';
return (
msg.includes('GIT_NOT_AVAILABLE') ||
+ msg.includes('GIT_PROBE_TIMEOUT') ||
msg.includes('GIT_TOO_OLD') ||
msg.includes('OpenKnowledge needs Git') ||
msg.includes('OpenKnowledge requires Git') ||
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index c7f22b46e..4d60b58a7 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -243,6 +243,7 @@ export {
fallbackPaths,
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
type InstallGuidance,
type InstallOption,
diff --git a/packages/server/src/local-ops/clone-flow.ts b/packages/server/src/local-ops/clone-flow.ts
index dee4ab3d3..fb9e5b54c 100644
--- a/packages/server/src/local-ops/clone-flow.ts
+++ b/packages/server/src/local-ops/clone-flow.ts
@@ -4,9 +4,13 @@ import {
assertGitAvailable,
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
} from '../git-preflight.ts';
-import { emitPreflightFailureSpan } from '../git-preflight-telemetry.ts';
+import {
+ describeGitPreflightFailure,
+ emitPreflightFailureSpan,
+} from '../git-preflight-telemetry.ts';
import { expandTilde, isAllowedGitUrl, isSafeLocalPath } from '../local-op-security.ts';
import { getLogger } from '../logger.ts';
import { redactedStderrDetail, stderrDetailSuffix } from './clone-error-classify.ts';
@@ -97,16 +101,21 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {
try {
detected = assertGitAvailable();
} catch (err) {
- if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ if (
+ err instanceof GitNotAvailableError ||
+ err instanceof GitProbeTimeoutError ||
+ err instanceof GitTooOldError
+ ) {
+ const failure = describeGitPreflightFailure(err);
emitPreflightFailureSpan(err);
log.warn(
{
event: 'git_preflight_fail',
platform: err.platform,
- reason: err instanceof GitTooOldError ? 'too_old' : 'not_available',
- detectedVersion: err instanceof GitTooOldError ? err.detected : '',
+ reason: failure.reason,
+ detectedVersion: failure.detectedVersion,
},
- err instanceof GitTooOldError ? 'git binary too old' : 'git binary not found',
+ failure.logMessage,
);
} else {
log.error(
diff --git a/packages/server/src/project-git.ts b/packages/server/src/project-git.ts
index f029cdf83..e98d48602 100644
--- a/packages/server/src/project-git.ts
+++ b/packages/server/src/project-git.ts
@@ -7,9 +7,13 @@ import {
assertGitAvailable,
type GitDetected,
GitNotAvailableError,
+ GitProbeTimeoutError,
GitTooOldError,
} from './git-preflight.ts';
-import { emitPreflightFailureSpan } from './git-preflight-telemetry.ts';
+import {
+ describeGitPreflightFailure,
+ emitPreflightFailureSpan,
+} from './git-preflight-telemetry.ts';
import { assertSafeProjectRoot } from './home-project-root.ts';
import { getLogger } from './logger.ts';
@@ -165,16 +169,21 @@ export async function ensureProjectGit(projectRoot: string): Promise<EnsureProje
try {
detected = assertGitAvailable();
} catch (err) {
- if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ if (
+ err instanceof GitNotAvailableError ||
+ err instanceof GitProbeTimeoutError ||
+ err instanceof GitTooOldError
+ ) {
+ const failure = describeGitPreflightFailure(err);
emitPreflightFailureSpan(err);
log.warn(
{
event: 'git_preflight_fail',
platform: err.platform,
- reason: err instanceof GitTooOldError ? 'too_old' : 'not_available',
- detectedVersion: err instanceof GitTooOldError ? err.detected : '',
+ reason: failure.reason,
+ detectedVersion: failure.detectedVersion,
},
- err instanceof GitTooOldError ? 'git binary too old' : 'git binary not found',
+ failure.logMessage,
);
} else {
log.warn(