Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): stop background sync from opening a GCM sign-in window on Windows (#2993)
mike-inkeepf8ad7b711319
diff --git a/.changeset/no-background-credential-popups.md b/.changeset/no-background-credential-popups.mdnew file mode 100644index 000000000..cb3effd16--- /dev/null+++ b/.changeset/no-background-credential-popups.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++Stop background sync from popping a GitHub sign-in window on Windows.++On Windows, a project with a GitHub remote could open a "GitHub — Select an account" window every few minutes, unprompted, for as long as the app was running — even while syncing was healthy and pushing successfully. The window came from Git Credential Manager, the credential helper Git for Windows installs by default, not from OpenKnowledge's own sign-in flow. OpenKnowledge already told git not to prompt, but that setting only silences git's own terminal prompt and does nothing about a credential helper's graphical prompt, so every background fetch that missed the credential store put a dialog on the desktop.++OpenKnowledge's own git commands now run fully non-interactively, so a missing or expired credential can no longer surface as a surprise system dialog. Instead it appears where it belongs: the sync status shows "reconnect to resume syncing" with a Sign in button, on your schedule rather than interrupting whatever you were doing. The same applies to opening a shared branch, where a credential dialog could previously outlive the fetch that raised it and sit on your desktop with nothing behind it. macOS and Linux were unaffected in practice, since their usual credential helpers never draw a window.diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex 09399d6b6..1103278fd 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -1,5 +1,13 @@import type { TerminalCli } from '@inkeep/open-knowledge-core';-import { lazy, Suspense, useEffect, useEffectEvent, useRef, useState } from 'react';+import {+ lazy,+ Suspense,+ useEffect,+ useEffectEvent,+ useRef,+ useState,+ useSyncExternalStore,+} from 'react';import { getEditorForDoc } from '@/editor/active-editor';import { EmojiInsertPopover } from '@/editor/components/EmojiInsertPopover';import { TagDialog } from '@/editor/components/TagDialog';@@ -14,6 +22,7 @@ import { useGitSyncStatus } from '@/hooks/use-git-sync-status';import { useInstalledClis } from '@/hooks/use-installed-clis';import { useNoPushPermissionToast } from '@/hooks/use-no-push-permission-toast';import { useWorktreeAutoSyncNotice } from '@/hooks/use-worktree-autosync-notice';+import { authPromptStore } from '@/lib/auth-prompt-store';import { useConfigContext } from '@/lib/config-provider';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';@@ -107,6 +116,24 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {const [editorMode, setEditorMode] = useState<EditorMode>(persistedMode);const [authModalOpen, setAuthModalOpen] = useState(false);const [authInitialStep, setAuthInitialStep] = useState<'auth' | 'identity'>('auth');+ // Sign-in requested by a surface with no prop path to this modal — today the+ // share branch-switch dialog's credential-miss toast, which mounts under App.+ // Return the store's value directly: discarding a useSyncExternalStore result+ // lets React Compiler memoize it to the first snapshot, freezing the flag.+ const authPromptPending = useSyncExternalStore(+ authPromptStore.subscribe,+ authPromptStore.getSnapshot,+ () => false,+ );+ useEffect(() => {+ if (!authPromptPending) return;+ // Clear first: the store is the request, not the modal's open state, so+ // leaving it armed would re-fire on every subsequent render and fight a+ // user who closes the modal.+ authPromptStore.clear();+ setAuthInitialStep('auth');+ setAuthModalOpen(true);+ }, [authPromptPending]);const [activeTab, setActiveTab] = useState<PanelTab>(TABS[0].id);const [autoSyncOnboardingDismissed, setAutoSyncOnboardingDismissed] = useState(false);// Bottom-docked terminal — desktop-only (the bridge is absent in the webdiff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsxindex c90536d87..362a936d0 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx@@ -38,6 +38,7 @@ import {Dialog as DialogRoot,DialogTitle,} from '@/components/ui/dialog';+import { authPromptStore } from '@/lib/auth-prompt-store';import {type OkDesktopBridge,type OkShareReceivedPayload,@@ -437,7 +438,21 @@ export function ShareBranchSwitchDialog({function showWorktreeFailureToast(reason: WorktreeCheckoutSideEffectReason,helper?: string,+ authFailed?: true,): void {+ // A credential miss reaches us as `fetch-failed`, but the connection copy+ // below is a dead end for it: the fetch pins credential interactivity off,+ // so nothing prompted the user, and retrying without a credential just+ // fails the same way. Offer the sign-in they actually need.+ if (reason === 'fetch-failed' && authFailed) {+ toast.error(t`Could not fetch branch — sign in to GitHub and try again.`, {+ action: {+ label: t`Sign in`,+ onClick: () => authPromptStore.request(),+ },+ });+ return;+ }switch (reason) {case 'helper-not-found': {// `helper` accompanies this reason from the classifier; the fallback@@ -489,6 +504,7 @@ export function ShareBranchSwitchDialog({function applyWorktreeOutcome(result: WorktreeCreateResult | null): void {let failureReason: WorktreeCheckoutSideEffectReason | null = null;let failureHelper: string | undefined;+ let failureAuth: true | undefined;let shouldDismiss = false;let openPath: string | null = null;setBranchSwitchState((prev) => {@@ -496,6 +512,7 @@ export function ShareBranchSwitchDialog({if (sideEffect) {failureReason = sideEffect.reason;failureHelper = sideEffect.helper;+ failureAuth = sideEffect.authFailed;shouldDismiss = next.phase === 'dismissed';}if (next.phase === 'opening-worktree') {@@ -510,7 +527,7 @@ export function ShareBranchSwitchDialog({branch: shareBranch,}),);- showWorktreeFailureToast(failureReason, failureHelper);+ showWorktreeFailureToast(failureReason, failureHelper, failureAuth);}if (openPath !== null) {// The anchor window's cached worktree model is stale now (a worktree wasdiff --git a/packages/app/src/lib/auth-prompt-store.ts b/packages/app/src/lib/auth-prompt-store.tsnew file mode 100644index 000000000..bef1690d2--- /dev/null+++ b/packages/app/src/lib/auth-prompt-store.ts@@ -0,0 +1,53 @@+/**+ * Renderer store for "something needs the user to sign in to GitHub".+ *+ * The AuthModal is owned locally by the surfaces that host it (EditorPane,+ * NavigatorApp) and opened from their own chrome. Surfaces that are mounted+ * elsewhere in the tree — `ShareBranchSwitchDialog` self-gates on the share+ * store under App, with no prop path to EditorPane's modal state — need a way+ * to ask for it without lifting that state through the whole tree.+ *+ * Same module-singleton + `useSyncExternalStore` shape as `miss-dialog-store`+ * and `receive-store`. `request()` arms it, the hosting surface opens its modal+ * and calls `clear()`.+ */++export interface AuthPromptStore {+ /** Ask the hosting surface to open the GitHub sign-in modal. */+ request(): void;+ /** Called by the host once it has opened the modal. */+ clear(): void;+ getSnapshot(): boolean;+ subscribe(listener: () => void): () => void;+}++function createAuthPromptStore(): AuthPromptStore {+ let pending = false;+ const listeners = new Set<() => void>();++ function set(next: boolean): void {+ if (pending === next) return;+ pending = next;+ for (const l of listeners) l();+ }++ return {+ request(): void {+ set(true);+ },+ clear(): void {+ set(false);+ },+ getSnapshot(): boolean {+ return pending;+ },+ subscribe(listener): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+}++export const authPromptStore: AuthPromptStore = createAuthPromptStore();diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.tsindex 6a89f38bd..2ddcc5939 100644--- a/packages/app/src/lib/share/branch-switch-flow.test.ts+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts@@ -671,6 +671,31 @@ describe('applyWorktreeCheckoutOutcome (worktree leg)', () => {expect(result.sideEffect).toEqual({ kind: 'toast', reason: 'fetch-failed' });});+ // A credential miss arrives as `fetch-failed` too, but the connection copy is+ // a dead end for it — the fetch pins interactivity off so nothing prompted the+ // user, and a retry without a credential fails identically. The flag is what+ // lets the dialog swap in sign-in copy plus a Sign in action.+ test('fetch-failed carrying authFailed propagates the flag so the toast can offer Sign in', () => {+ const result = applyWorktreeCheckoutOutcome(creating, {+ ok: false,+ reason: 'fetch-failed',+ authFailed: true,+ });+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });+ expect(result.sideEffect?.authFailed).toBe(true);+ expect(result.sideEffect?.reason).toBe('fetch-failed');+ });++ test('fetch-failed without the flag leaves authFailed unset (network case keeps the retry copy)', () => {+ const result = applyWorktreeCheckoutOutcome(creating, { ok: false, reason: 'fetch-failed' });+ expect(result.sideEffect?.authFailed).toBeUndefined();+ });++ test('a non-fetch reason can never carry authFailed through the reducer', () => {+ const result = applyWorktreeCheckoutOutcome(creating, { ok: false, reason: 'no-git' });+ expect(result.sideEffect?.authFailed).toBeUndefined();+ });+test('branch-not-found dismisses with the branch-gone toast signal (terminal, mirrors the switch leg)', () => {const result = applyWorktreeCheckoutOutcome(creating, {ok: false,diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.tsindex 887c72e94..423782616 100644--- a/packages/app/src/lib/share/branch-switch-flow.ts+++ b/packages/app/src/lib/share/branch-switch-flow.ts@@ -579,6 +579,11 @@ export interface ApplyWorktreeCheckoutOutcomeResult {/** Set iff `reason === 'helper-not-found'` — the missing command git* reported (e.g. `git-lfs`), interpolated into the toast copy. */readonly helper?: string;+ /** Set iff `reason === 'fetch-failed'` AND the fetch failed for want of a+ * credential rather than for a network reason. Swaps the connection copy+ * for sign-in copy plus a Sign in action — retrying without a credential+ * just fails again. */+ readonly authFailed?: true;};}@@ -623,6 +628,13 @@ export function applyWorktreeCheckoutOutcome(}return {state: { phase: 'ready', info: state.info },- sideEffect: { kind: 'toast', reason: result.reason, helper: result.helper },+ sideEffect: {+ kind: 'toast',+ reason: result.reason,+ helper: result.helper,+ // Only `fetch-failed` carries this (its own arm on WorktreeCreateResult);+ // every other reason narrows to `undefined` here.+ authFailed: result.reason === 'fetch-failed' ? result.authFailed : undefined,+ },};}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 05ebde107..7f85f99c5 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -2548,6 +2548,7 @@"gZElfU": ["Fixing ", ["0"], " of ", ["1"], " files"],"gZiT5e": ["Replace these symlinks with independent copies?"],"gbHcbI": ["Failed to delete property"],+ "gfb-CM": ["Could not fetch branch — sign in to GitHub and try again."],"gfdqcY": ["Couldn't apply the change: ", ["0"]],"gfohmY": ["Connect tools"],"ggm6JX": [diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex dbf23eb16..b39430f18 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -2749,6 +2749,10 @@ msgstr "Could not enable sync: {detail}"msgid "Could not enable the terminal: {0}"msgstr "Could not enable the terminal: {0}"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not fetch branch — sign in to GitHub and try again."+msgstr "Could not fetch branch — sign in to GitHub and try again."+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Could not fetch branch. Check your connection."msgstr "Could not fetch branch. Check your connection."@@ -9692,6 +9696,7 @@ msgstr "Shows above the code body. Round-trips as `title=\"...\"` in markdown."#: src/components/settings/AccountSection.tsx#: src/components/settings/SyncSection.tsx+#: src/components/ShareBranchSwitchDialog.tsx#: src/components/SyncStatusBadge.tsxmsgid "Sign in"msgstr "Sign in"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 32815df10..e9a410097 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -2548,6 +2548,7 @@"gZElfU": ["Ƒĩxĩńĝ ", ["0"], " ōƒ ", ["1"], " ƒĩĺēś"],"gZiT5e": ["Ŕēƥĺàćē ţĥēśē śŷḿĺĩńķś ŵĩţĥ ĩńďēƥēńďēńţ ćōƥĩēś?"],"gbHcbI": ["Ƒàĩĺēď ţō ďēĺēţē ƥŕōƥēŕţŷ"],+ "gfb-CM": ["Ćōũĺď ńōţ ƒēţćĥ ƀŕàńćĥ — śĩĝń ĩń ţō ĜĩţĤũƀ àńď ţŕŷ àĝàĩń."],"gfdqcY": ["Ćōũĺďń'ţ àƥƥĺŷ ţĥē ćĥàńĝē: ", ["0"]],"gfohmY": ["Ćōńńēćţ ţōōĺś"],"ggm6JX": [diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 7e36cdc5e..fed329ddf 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -2745,6 +2745,10 @@ msgstr ""msgid "Could not enable the terminal: {0}"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not fetch branch — sign in to GitHub and try again."+msgstr ""+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Could not fetch branch. Check your connection."msgstr ""@@ -9688,6 +9692,7 @@ msgstr ""#: src/components/settings/AccountSection.tsx#: src/components/settings/SyncSection.tsx+#: src/components/ShareBranchSwitchDialog.tsx#: src/components/SyncStatusBadge.tsxmsgid "Sign in"msgstr ""diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.tsindex 1e7dcf26a..d631b5798 100644--- a/packages/core/src/git/worktree-selector-model.ts+++ b/packages/core/src/git/worktree-selector-model.ts@@ -136,6 +136,25 @@ export type WorktreeCreateResult =readonly helper: string;readonly message?: string;}+ | {+ readonly ok: false;+ readonly reason: 'fetch-failed';+ readonly message?: string;+ readonly helper?: never;+ /**+ * Set when the fetch failed for want of a usable credential rather than+ * for a network/timeout reason, and re-authenticating could plausibly fix+ * it (`isLoginFixableGitAuthError` — so not 403, scope-mismatch, or SSH+ * key failures, which a sign-in doesn't repair).+ *+ * Its own arm rather than a field on the shared failure arm below: only+ * `fetch-failed` reaches git's credential stage, so no other reason can+ * structurally carry the flag. Optional and additive — a producer that+ * omits it degrades to the generic connection-flavored copy, which is the+ * pre-existing behavior.+ */+ readonly authFailed?: true;+ }| {readonly ok: false;readonly reason:@@ -145,7 +164,6 @@ export type WorktreeCreateResult =| 'path-exists'| 'no-git'| 'branch-not-found'- | 'fetch-failed'| 'error';readonly message?: string;readonly helper?: never;diff --git a/packages/core/src/schemas/api/share.test.ts b/packages/core/src/schemas/api/share.test.tsindex 789169c7b..ab45cb77f 100644--- a/packages/core/src/schemas/api/share.test.ts+++ b/packages/core/src/schemas/api/share.test.ts@@ -57,6 +57,21 @@ describe('classifyGitAuthError', () => {});});+ test('classifies GCM\'s "user interactivity has been disabled" as no-credential', () => {+ expect(+ classifyGitAuthError(+ new Error('fatal: Cannot prompt because user interactivity has been disabled.'),+ ),+ ).toEqual({ kind: 'auth', subclass: 'no-credential' });+ });++ test('classifies "unable to get password from user" as no-credential', () => {+ expect(classifyGitAuthError(new Error('fatal: unable to get password from user'))).toEqual({+ kind: 'auth',+ subclass: 'no-credential',+ });+ });+test('classifies HTTP 401 as 401', () => {expect(classifyGitAuthError(new Error('remote: HTTP 401 Unauthorized'))).toEqual({kind: 'auth',diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.tsindex a4b12edba..45dcd7d72 100644--- a/packages/core/src/schemas/api/share.ts+++ b/packages/core/src/schemas/api/share.ts@@ -431,9 +431,21 @@ export type ClassifiedGitAuthError =| { kind: 'auth'; subclass: GitAuthFailureSubclass }| { kind: 'non-auth' };+// The last two appear once `credential.interactive=false` is pinned (see+// `createGitInstance`). Both layers that honor the key contribute a string:+// Git Credential Manager declines its dialog with "Cannot prompt because user+// interactivity has been disabled", and git's own `credential_getpass`+// short-circuits with "unable to get password from user" instead of the+// TTY-flavored "could not read Username … terminal prompts disabled".+// The git-side substitution happens on EVERY platform, not just Windows, so+// dropping these would silently reclassify an ordinary macOS/Linux credential+// miss as a retryable unknown. Same condition as the first two — no usable+// credential — so all four must reach the `auth-error` + "Sign in" surface.const GIT_AUTH_NO_CREDENTIAL_PATTERNS: RegExp[] = [/could not read (username|password)/i,/terminal prompts disabled/i,+ /user interactivity has been disabled/i,+ /unable to get password from user/i,];const GIT_AUTH_SCOPE_MISMATCH_PATTERNS: RegExp[] = [diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.tsindex b41442788..0480f6157 100644--- a/packages/desktop/src/main/worktree-service.test.ts+++ b/packages/desktop/src/main/worktree-service.test.ts@@ -17,6 +17,7 @@ import { afterEach, describe, expect, test } from 'vitest';import { discoverProject } from './folder-admission.ts';import { clearRecentGitCache } from './worktree-recents.ts';import {+ buildShareFetchArgs,checkoutShareBranchWorktree,createWorktree,listWorktreeSelector,@@ -702,6 +703,26 @@ describe('worktree-service — share-branch checkout', () => {expect(await repoSnapshot(handle.mainRepo)).toEqual(before);});+ // Regression: desktop main has no terminal AND must never put an OS credential+ // dialog on screen. GIT_TERMINAL_PROMPT (set in the spawn env) only covers+ // git's own TTY prompt; an interactive helper like Git Credential Manager —+ // wired in by default on Git for Windows — would still open a sign-in window,+ // which the timeout kill below would then strand on the desktop.+ //+ // SCOPE, stated so it isn't over-read: this pins the builder's output only. It+ // does NOT prove `fetchShareBranch` calls the builder — reverting that call+ // site to a bare ['fetch','origin',branch] would still pass. Proving usage+ // needs either a child_process mock (which would fight the real-git spawns+ // every other test here depends on) or a remote that reaches git's credential+ // path, whose stderr differs by git version (2.54 honors the pin, 2.39 does+ // not) and so can't be asserted portably across dev machines.+ test('share fetch pins credential interactivity off so no helper can open a dialog', () => {+ const args = buildShareFetchArgs('feat-x');+ expect(args).toEqual(['-c', 'credential.interactive=false', 'fetch', 'origin', 'feat-x']);+ // The pin must PRECEDE the subcommand — git only reads `-c` before it.+ expect(args.indexOf('-c')).toBeLessThan(args.indexOf('fetch'));+ });+// fetch-leg failure, terminal class: the branch never existed on origin, so// git reports "couldn't find remote ref" and the checkout returns the// terminal branch-not-found — with nothing created locally.@@ -743,6 +764,39 @@ describe('worktree-service — share-branch checkout', () => {expect(res.reason).toBe('fetch-failed');expect(typeof res.message).toBe('string');expect((res.message ?? '').length).toBeGreaterThan(0);+ // A genuine network failure must NOT be flagged as auth — offering "Sign in"+ // for an unreachable remote sends the user somewhere that can't help.+ expect(res.authFailed).toBeUndefined();+ expect(existsSync(join(handle.mainRepo, '.ok', 'worktrees', 'any-branch'))).toBe(false);+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);+ });++ // The credential-miss arm. Since the fetch pins interactivity off, no helper+ // prompts and git fails with a no-credential stderr — which must reach the+ // dialog as `authFailed` so it offers Sign in instead of "check your+ // connection". Driven through a real `git fetch` via an ext:: transport that+ // emits git's own no-credential wording, so the classifier is exercised on a+ // real spawn without needing the network or a live credential helper.+ test('checkoutShareBranchWorktree flags a credential miss as authFailed', async () => {+ handle = await makeRepo();+ const faultyRemote = join(handle.root, 'no-cred-remote.sh');+ writeFileSync(+ faultyRemote,+ '#!/bin/sh\necho "fatal: could not read Username for \'https://github.com\': terminal prompts disabled" >&2\nexit 1\n',+ { mode: 0o755 },+ );+ await git(handle.mainRepo, 'config', 'protocol.ext.allow', 'always');+ await git(handle.mainRepo, 'remote', 'add', 'origin', `ext::${faultyRemote}`);+ const before = await repoSnapshot(handle.mainRepo);++ const res = await checkoutShareBranchWorktree({+ anchorPath: handle.mainRepo,+ branch: 'any-branch',+ });+ expect(res.ok).toBe(false);+ if (res.ok) return;+ expect(res.reason).toBe('fetch-failed');+ expect(res.authFailed).toBe(true);expect(existsSync(join(handle.mainRepo, '.ok', 'worktrees', 'any-branch'))).toBe(false);expect(await repoSnapshot(handle.mainRepo)).toEqual(before);});@@ -756,9 +810,10 @@ describe('worktree-service — share-branch checkout', () => {test('checkoutShareBranchWorktree kills a hanging fetch at the injected timeout (fetch-failed)', async () => {handle = await makeRepo();// ext:: transports are disallowed by default on modern git; opt in via- // repo config so the service's plain `git fetch` spawn (no -c flags)- // honors it. git-remote-ext splits the address on spaces with no shell,- // so `ext::sleep 60` runs `sleep` with argument `60`.+ // repo config, which the service's fetch spawn honors — its only `-c` flag+ // is the credential-interactivity pin, which doesn't touch protocol.ext.+ // git-remote-ext splits the address on spaces with no shell, so+ // `ext::sleep 60` runs `sleep` with argument `60`.await git(handle.mainRepo, 'config', 'protocol.ext.allow', 'always');await git(handle.mainRepo, 'remote', 'add', 'origin', 'ext::sleep 60');writeFileSync(join(handle.mainRepo, 'wip.txt'), 'uncommitted work\n');diff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.tsindex f4af43856..0fd51c49d 100644--- a/packages/desktop/src/main/worktree-service.ts+++ b/packages/desktop/src/main/worktree-service.ts@@ -27,8 +27,10 @@ import { isAbsolute, join, sep } from 'node:path';import { promisify } from 'node:util';import {buildWorktreeSelectorModel,+ classifyGitAuthError,detectMissingGitHelper,isBranchNotFoundGitError,+ isLoginFixableGitAuthError,isValidBranchName,parseBranchList,stripRemotePrefix,@@ -51,11 +53,36 @@ const execFileAsync = promisify(execFile);* credential prompt, so a credentialed remote must fail fast (into the* `fetch-failed` arm) instead of stalling until the timeout kill. Built per* call, never frozen at module level: `gitSpawnEnv()` must reflect the- * startup `SSH_AUTH_SOCK` harvest (see `git-spawn-env.ts`). */+ * startup `SSH_AUTH_SOCK` harvest (see `git-spawn-env.ts`).+ *+ * THIS ENV IS HALF THE GUARANTEE. `GIT_TERMINAL_PROMPT=0` silences git's own+ * terminal prompt and nothing else — a credential helper's GUI is untouched by+ * it. Any remote-capable spawn using this env must ALSO carry+ * `-c credential.interactive=false` in argv (see `buildShareFetchArgs`), or an+ * interactive helper can still open a sign-in window. */function fetchGitEnv(): Record<string, string | undefined> {return { ...gitSpawnEnv(), GIT_TERMINAL_PROMPT: '0' };}+/**+ * argv for the share-branch fetch.+ *+ * The `-c credential.interactive=false` prefix is the other half of "fail fast,+ * don't prompt": `GIT_TERMINAL_PROMPT` covers git's own TTY prompt but not a+ * credential helper's GUI, and Git for Windows wires interactive Git Credential+ * Manager in by default. Without it this bounded fetch could put a GitHub+ * sign-in window on screen — and the timeout kill would strand that window+ * there, outliving the operation that raised it. Honored by git itself as well+ * as by GCM, so both layers decline. Mirrors the server's `createGitInstance`+ * pin.+ *+ * Exported as a pure builder so the pin is asserted directly, without mocking+ * the spawn that every other test in this file drives through real git.+ */+export function buildShareFetchArgs(branch: string): string[] {+ return ['-c', 'credential.interactive=false', 'fetch', 'origin', branch];+}+/** Default bound for the share-checkout fetch — matches the server's* fast-forward fetch bound so a stalled network degrades to a typed* `fetch-failed` instead of an indefinite hang. Injectable per call so tests@@ -319,7 +346,7 @@ async function fetchShareBranch(timeoutMs: number,): Promise<Extract<WorktreeCreateResult, { ok: false }> | null> {try {- await execFileAsync('git', ['fetch', 'origin', branch], {+ await execFileAsync('git', buildShareFetchArgs(branch), {cwd: anchorPath,env: fetchGitEnv(),timeout: timeoutMs,@@ -333,10 +360,19 @@ async function fetchShareBranch(const killed = (err as { killed?: boolean }).killed === true;const signal = (err as { signal?: string }).signal;const raw = gitErrorText(err).replace(/\s+/g, ' ').slice(0, 280);+ // A credential miss is not a connection problem, and telling the user to+ // check their network when they need to sign in is a dead end — doubly so+ // since `buildShareFetchArgs` pins interactivity off, so no helper will+ // prompt them here. Flag it so the dialog can offer Sign in instead. Gated+ // on login-fixable: a 403 or a bad SSH key is an auth failure that signing+ // in again does not repair, and offering it would be the same dead end.+ const classified = classifyGitAuthError(err);+ const authFailed = isLoginFixableGitAuthError(classified);return {ok: false,reason: 'fetch-failed',message: killed ? `[timeout signal=${signal ?? 'SIGTERM'}] ${raw}` : raw,+ ...(authFailed ? { authFailed: true as const } : {}),};}}diff --git a/packages/server/src/error-classification.test.ts b/packages/server/src/error-classification.test.tsindex 719d2e2f3..112084a36 100644--- a/packages/server/src/error-classification.test.ts+++ b/packages/server/src/error-classification.test.ts@@ -157,6 +157,34 @@ describe('classifyGitError', () => {expect(r.subclass).toBe('no-credential');});+ // Verbatim stderr from a Windows 11 + Git 2.54 + Git Credential Manager+ // fetch once `credential.interactive=false` is pinned. GCM declines the+ // prompt rather than opening its sign-in window, so this is now the normal+ // shape of "no credential" and must not degrade to a retryable unknown+ // (which would silently retry forever with no "Sign in" affordance).+ // The second line is git's own, not GCM's, so a credential miss takes this+ // shape on macOS/Linux too — it is not a Windows-only case.+ test('no credential — GCM declines to prompt (credential.interactive=false)', () => {+ const r = classifyGitError(+ mkErr(+ 'fatal: Cannot prompt because user interactivity has been disabled.',+ 'fatal: Cannot prompt because user interactivity has been disabled.\nfatal: unable to get password from user',+ ),+ );+ expect(r.class).toBe('auth');+ expect(r.subclass).toBe('no-credential');+ expect(r.retryable).toBe(false);+ expect(r.userFacingCode).toBe('auth-no-credential');+ });++ test('no credential — "unable to get password from user" alone', () => {+ const r = classifyGitError(mkErr('fatal: unable to get password from user'));+ expect(r.class).toBe('auth');+ expect(r.subclass).toBe('no-credential');+ expect(r.retryable).toBe(false);+ expect(r.userFacingCode).toBe('auth-no-credential');+ });+test('deriveUserFacingCode maps auth/no-credential', () => {expect(deriveUserFacingCode('auth', 'no-credential')).toBe('auth-no-credential');});diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.tsindex aa8385683..d619279be 100644--- a/packages/server/src/git-handle.test.ts+++ b/packages/server/src/git-handle.test.ts@@ -37,8 +37,11 @@ describe('buildGitEnv', () => {test('disables terminal prompts (no-TTY server-spawned git)', () => {// Without this, a credential-less fetch/push opens /dev/tty and dies with- // "could not read Username … Device not configured". Disabled, git- // fail-fasts with "terminal prompts disabled".+ // "could not read Username … Device not configured". Retained as the second+ // line of defence: `createGitInstance` pins `credential.interactive=false`,+ // which short-circuits earlier on git versions that honor it, so this var+ // is what keeps the misleading ENXIO errno out of logs on the paths and git+ // versions the pin doesn't cover.expect(buildGitEnv().GIT_TERMINAL_PROMPT).toBe('0');});@@ -173,6 +176,31 @@ describe('createGitInstance (credential.helper config)', () => {expect((await handle.git.raw(['config', '--get', 'commit.gpgsign'])).trim()).toBe('false');expect((await handle.git.raw(['config', '--get', 'core.autocrlf'])).trim()).toBe('false');});++ // Regression: a server-spawned git must never be able to open a credential+ // helper's GUI. `GIT_TERMINAL_PROMPT=0` only silences git's own TTY prompt;+ // Git Credential Manager (the default helper on Git for Windows, and+ // interactive by default) would still pop a GitHub sign-in window on every+ // background fetch that missed the credential store.+ test('pins credential.interactive off, overriding repo config', async () => {+ execSync('git config credential.interactive true', { cwd: tmpDir });++ const handle = createGitInstance(tmpDir);+ expect((await handle.git.raw(['config', '--get', 'credential.interactive'])).trim()).toBe(+ 'false',+ );+ });++ test('keeps pinning credential.interactive off alongside a credential.helper arg', async () => {+ // The helper arg is spliced into the same `-c` list; splicing must not+ // displace the interactivity pin.+ const handle = createGitInstance(tmpDir, {+ credentialArgs: ['-c', 'credential.helper=!open-knowledge auth git-credential'],+ });+ expect((await handle.git.raw(['config', '--get', 'credential.interactive'])).trim()).toBe(+ 'false',+ );+ });});describe('withParentLock', () => {diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.tsindex fa4223f80..e1bfb00bb 100644--- a/packages/server/src/git-handle.ts+++ b/packages/server/src/git-handle.ts@@ -132,9 +132,14 @@ const GIT_AUTH_ENV_KEYS = [* controlling terminal, so when the credential helper returns nothing, an* attempted prompt fails with the alarming "could not read Username … Device* not configured" (an ENXIO on `/dev/tty`). Disabling prompts makes git- * fail-fast with "terminal prompts disabled" instead, which the error- * classifier maps to the reconnect-required auth state. Both strings classify- * as no-credential, but this avoids a misleading errno in logs and the UI.+ * fail-fast instead, which the error classifier maps to the reconnect-required+ * auth state. It is the SECOND line of defence, not the first: `createGitInstance`+ * pins `credential.interactive=false`, which on git versions that honor it+ * short-circuits in `credential_getpass` before the terminal path is reached — so+ * the string the server emits there is "unable to get password from user", not+ * "terminal prompts disabled". Both classify as no-credential; this var is what+ * covers the paths and git versions the pin doesn't, keeping the misleading+ * ENXIO errno out of logs and the UI.** `GIT_MERGE_AUTOEDIT=no` is set unconditionally for the same non-interactive* reason: `sync-engine`'s `git merge origin/<branch>` is the one sync op that@@ -203,6 +208,14 @@ export function applyGitEnv(* Create a SimpleGit instance rooted at `projectDir` with optional credential* args and index file isolation. Env construction (and the reasons each var is* preserved through simple-git's env replacement) lives in `buildGitEnv`.+ *+ * This factory is the sanctioned path for any server-side git that CAN REACH A+ * REMOTE. It is the only place the non-interactivity guarantees are assembled+ * (`GIT_TERMINAL_PROMPT=0` + `credential.interactive=false`), and a remote-capable+ * spawn without them can put an OS credential dialog on the user's desktop from a+ * process they can't see. Bare `simpleGit(...)` elsewhere in the server is fine+ * for local-only work (log reads, shadow-ref plumbing) — but the moment such a+ * call site grows a `fetch`/`push`/`ls-remote`, it must move to this factory.*/export function createGitInstance(projectDir: string, options: GitHandleOptions = {}): GitHandle {const { credentialArgs = [], gitIndexFile, ghToken, timeoutMs } = options;@@ -213,7 +226,7 @@ export function createGitInstance(projectDir: string, options: GitHandleOptions}// Server-spawned git inherits the user's ~/.gitconfig (buildGitEnv keeps- // HOME so SSH keys and credential helpers resolve). Pin two of its directives+ // HOME so SSH keys and credential helpers resolve). Pin three of its directives// OFF for OK's git only — `-c` outranks global config, and the user's own// terminal/IDE git is untouched:// - commit.gpgsign: the merge-resolution `git commit` would GPG-sign with no@@ -222,9 +235,24 @@ export function createGitInstance(projectDir: string, options: GitHandleOptions// bot-authored commit with the user's key.// - core.autocrlf: would rewrite content EOLs on checkout/merge, fighting the// byte-exact LF round-trip and churning the file-watcher <-> CRDT path.+ // - credential.interactive: the companion to buildGitEnv's+ // `GIT_TERMINAL_PROMPT=0`, which only governs git's OWN terminal prompt and+ // does nothing to a credential helper's GUI. Git for Windows ships+ // `credential.helper=manager` in its system config, and Git Credential+ // Manager is interactive by default, so any credential miss on a background+ // fetch opened a GitHub sign-in WINDOW on the user's desktop with no user+ // action — every ~30s pull tick, for a daemon the user can't see.+ // Honored at BOTH layers: git's own `credential_getpass` short-circuits on+ // it, and GCM reads it to decline its dialog. So the miss surfaces as OK's+ // `auth-error` + "Sign in" affordance instead of an OS prompt.+ // Cross-platform consequence: on git versions that honor it (measured:+ // 2.54 does, 2.39 doesn't) this REPLACES the "terminal prompts disabled"+ // stderr with "unable to get password from user" everywhere, not just on+ // Windows — `GIT_AUTH_NO_CREDENTIAL_PATTERNS` must keep matching both.const gitConfig = ['commit.gpgsign=false','core.autocrlf=false',+ 'credential.interactive=false',...(credentialArgs.length >= 2 ? [credentialArgs[1]] : []),];