Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(windows): publish fallback runs only 'gh auth login' and retries in-process
reviewb77c07d6f85a
diff --git a/src/core/git-service.publish-auth.test.ts b/src/core/git-service.publish-auth.test.tsnew file mode 100644index 000000000..3c0c06f56--- /dev/null+++ b/src/core/git-service.publish-auth.test.ts@@ -0,0 +1,50 @@+import fs from 'fs'+import os from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Source Control retries `publish` right after running `gh auth login` in a terminal+// (renderer/lib/publishFallback). A cached "not signed in" must not outlive that login.+let fakeGh = ''+vi.mock('./gh-path', () => ({ ghPath: () => fakeGh }))++describe.skipIf(process.platform === 'win32')('GitService.publish — gh auth after a terminal login', () => {+ let dir: string+ const saved: Record<string, string | undefined> = {}+ const ENV = ['HOME', 'XDG_CONFIG_HOME', 'GIT_CONFIG_NOSYSTEM', 'GIT_CONFIG_GLOBAL']++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-gh-auth-'))+ for (const k of ENV) saved[k] = process.env[k]+ // No git credential helper may answer for this test: the token fallback must find nothing.+ process.env.HOME = dir+ process.env.XDG_CONFIG_HOME = dir+ process.env.GIT_CONFIG_NOSYSTEM = '1'+ process.env.GIT_CONFIG_GLOBAL = path.join(dir, 'no-gitconfig')+ fakeGh = path.join(dir, 'gh')+ fs.writeFileSync(+ fakeGh,+ `#!/bin/sh\nif [ "$1" = auth ]; then [ -f '${dir}/authed' ] && exit 0; exit 1; fi\necho "$@" >> '${dir}/calls'\nexit 0\n`,+ { mode: 0o755 }+ )+ })++ afterEach(() => {+ for (const k of ENV) {+ if (saved[k] === undefined) delete process.env[k]+ else process.env[k] = saved[k]+ }+ fs.rmSync(dir, { recursive: true, force: true })+ vi.resetModules()+ })++ it('re-asks gh after a cached negative, so the post-login retry publishes', async () => {+ vi.resetModules()+ const { GitService } = await import('./git-service')+ const git = new GitService()+ await expect(git.publish(dir, 'owner/repo', true)).resolves.toMatchObject({ ok: false, needsAuth: true })+ fs.writeFileSync(path.join(dir, 'authed'), '')+ await expect(git.publish(dir, 'owner/repo', true)).resolves.toEqual({ ok: true, message: 'Published to GitHub.' })+ expect(fs.readFileSync(path.join(dir, 'calls'), 'utf8').trim()).toBe('repo create owner/repo --private --source=. --push')+ })+})diff --git a/src/core/git-service.ts b/src/core/git-service.tsindex 58ac252dd..7081f39a7 100644--- a/src/core/git-service.ts+++ b/src/core/git-service.ts@@ -55,11 +55,12 @@ const GH_AUTH_TTL_MS = 10 * 60_000let ghAuthedCache: { value: boolean; at: number } | null = nulllet ghAuthedInFlight: Promise<boolean> | null = null-async function ghAuthed(): Promise<boolean> {+async function ghAuthed(opts?: { recheckNegative?: boolean }): Promise<boolean> {const invocation = ghInvocation(['auth', 'status'])if (!invocation) return falseconst now = Date.now()- if (ghAuthedCache && now - ghAuthedCache.at < GH_AUTH_TTL_MS) return ghAuthedCache.value+ const trusted = ghAuthedCache && (ghAuthedCache.value || !opts?.recheckNegative)+ if (ghAuthedCache && trusted && now - ghAuthedCache.at < GH_AUTH_TTL_MS) return ghAuthedCache.valueif (ghAuthedInFlight) return ghAuthedInFlightghAuthedInFlight = (async () => {let value = false@@ -819,7 +820,10 @@ export class GitService {// (the one that already lets them push) so publishing doesn't demand a separate// `gh auth login`. If neither is available, signal the UI to start a login.const env: NodeJS.ProcessEnv = { ...GIT_ENV }- if (!(await ghAuthed())) {+ // A cached "not signed in" is re-asked here: publish is user-initiated, and the Source Control+ // panel retries it right after running `gh auth login` in a terminal — trusting a 10-minute-old+ // negative would make that retry fail for the rest of the TTL.+ if (!(await ghAuthed({ recheckNegative: true }))) {const token = await githubTokenFromGitCredentials(cwd)if (!token) {return { ok: false, message: 'Sign in to GitHub to publish.', needsAuth: true }diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsxindex 4efb040ce..8d25231fc 100644--- a/src/renderer/components/SourceControlPanel.tsx+++ b/src/renderer/components/SourceControlPanel.tsx@@ -22,6 +22,7 @@ import { chipFor, effectiveBindings } from '../lib/keybindingOverrides'import { matchesShortcut } from '@shared/shortcut'import { isMacPlatform } from '@shared/platform-utils'import { gitStatusColor } from '../lib/gitStatusColors'+import { pendingPublish, publishOutcome, startPublishRetry, type PendingPublish } from '../lib/publishFallback'export interface SourceControlPanelProps {onClose: () => void@@ -126,6 +127,10 @@ export function SourceControlPanel({null)const [publishOpen, setPublishOpen] = useState(false)+ // A Publish waiting for `gh auth login` in a terminal and retrying in-process (see+ // lib/publishFallback). The retry outlives this drawer — the user closes it to reach the terminal+ // — so a reopened panel picks the pending one up and shows it.+ const [publishWait, setPublishWait] = useState<PendingPublish | null>(null)const [moreMenu, setMoreMenu] = useState<{ x: number; y: number } | null>(null)const [branchPick, setBranchPick] = useState<{x: number@@ -220,6 +225,21 @@ export function SourceControlPanel({refreshingRef.current = false}}, [])+ // Pick up a Publish retry still waiting for gh login (started before this drawer reopened).+ useEffect(() => {+ const p = cwd ? pendingPublish(cwd) : undefined+ setPublishWait(p ?? null)+ if (!p) return+ let live = true+ void p.done.then((r) => {+ if (!live) return+ setPublishWait(null)+ if (r.kind === 'published') void requestRefreshAll()+ })+ return () => {+ live = false+ }+ }, [cwd, requestRefreshAll])// Auto-fetch while the panel is open so ahead/behind ("Synced") stays accurate — git's ahead/// behind is computed against the local remote-tracking ref, which only updates on `git fetch`.@@ -484,6 +504,25 @@ export function SourceControlPanel({{/* Surface git action errors (e.g. a branch switch blocked by local changes)at the top, right under the repo/branch bar, so the user sees why theaction they just triggered failed instead of missing it at the bottom. */}+ {publishWait && (+ <div className="scm-error scm-error--info" role="status">+ <pre className="scm-error__msg">+ Finish signing in to GitHub in the terminal — the repository is created and pushed as soon as+ you are signed in.+ </pre>+ <button+ className="scm-error__dismiss"+ title="Stop waiting"+ aria-label="Stop waiting for GitHub sign-in"+ onClick={() => {+ publishWait.abort()+ setPublishWait(null)+ }}+ >+ <IconClose />+ </button>+ </div>+ )}{(error || genError) && (<div className="scm-error" role="alert"><pre className="scm-error__msg">{error || genError}</pre>@@ -918,25 +957,38 @@ export function SourceControlPanel({// Always try in-app: publish() reuses gh's login OR the user's existing git// HTTPS token, so an already-authenticated user never sees a terminal.setBusy(true)- const r = await git.publish(cwd!, name, isPrivate)+ const publishCwd = cwd!+ const first = publishOutcome(await git.publish(publishCwd, name, isPrivate))setBusy(false)- if (r.ok) {+ if (first.kind === 'published') {setError('')await requestRefreshAll()return}- if (r.needsAuth) {- // No usable credential (e.g. SSH-only): fall back to an interactive gh- // login chained straight into creating + pushing the chosen repo.- const safe = name.replace(/'/g, `'\\''`)- onRunInTerminal(- `gh auth login && gh repo create '${safe}' ${isPrivate ? '--private' : '--public'} --source=. --push`,- cwd!- )- onClose()+ if (first.kind === 'error') {+ setError(first.message)return}- setError(r.message)+ // No usable credential (e.g. SSH-only): run ONLY `gh auth login` in a terminal — a bare+ // command every shell parses the same, PowerShell and cmd included — and retry the+ // create + push in-process once the login lands (the repo name never meets a shell).+ // Errors surface as a toast: by then this drawer is usually closed.+ onRunInTerminal(first.terminalCmd, publishCwd)+ startPublishRetry(+ publishCwd,+ () => git.publish(publishCwd, name, isPrivate),+ (r) => {+ const message =+ r.kind === 'error'+ ? `Publish to GitHub failed: ${r.message}`+ : r.kind === 'timeout'+ ? 'Still not signed in to GitHub. Finish `gh auth login`, then choose Publish to GitHub again.'+ : null+ if (message) window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))+ }+ )+ setError('')+ onClose()}}/>)}diff --git a/src/renderer/lib/publishFallback.test.ts b/src/renderer/lib/publishFallback.test.tsnew file mode 100644index 000000000..0fd978a99--- /dev/null+++ b/src/renderer/lib/publishFallback.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest'+import type { GitResult } from '@shared/types'+import {+ GH_LOGIN_COMMAND,+ pendingPublish,+ publishOutcome,+ retryPublishAfterLogin,+ startPublishRetry+} from './publishFallback'++const AUTH: GitResult = { ok: false, message: 'Sign in to GitHub to publish.', needsAuth: true }+const OK: GitResult = { ok: true, message: 'Published to GitHub.' }++/** A publish that answers from a script, recording how often it ran. */+function scripted(...answers: GitResult[]) {+ let calls = 0+ return {+ publish: async () => answers[Math.min(calls++, answers.length - 1)],+ calls: () => calls+ }+}++const instant = { sleep: async () => undefined }++describe('publishOutcome', () => {+ it('asks for a terminal login that is ONE bare command — no chaining, quoting or repo name', () => {+ const o = publishOutcome(AUTH)+ expect(o).toEqual({ kind: 'login', terminalCmd: 'gh auth login' })+ expect(GH_LOGIN_COMMAND).not.toMatch(/&&|;|'|"|\|/)+ })+ it('passes success and non-auth failures through', () => {+ expect(publishOutcome(OK)).toEqual({ kind: 'published' })+ expect(publishOutcome({ ok: false, message: 'name taken' })).toEqual({ kind: 'error', message: 'name taken' })+ })+})++describe('retryPublishAfterLogin', () => {+ it('retries while gh still needs auth, and stops at the first success', async () => {+ const s = scripted(AUTH, AUTH, OK, OK)+ const r = await retryPublishAfterLogin(s.publish, { signal: new AbortController().signal, ...instant })+ expect(r).toEqual({ kind: 'published' })+ expect(s.calls()).toBe(3)+ })+ it('stops on a failure that is not about auth', async () => {+ const s = scripted(AUTH, { ok: false, message: 'Invalid repository name.' })+ const r = await retryPublishAfterLogin(s.publish, { signal: new AbortController().signal, ...instant })+ expect(r).toEqual({ kind: 'error', message: 'Invalid repository name.' })+ })+ it('gives up when the window closes', async () => {+ let t = 0+ const s = scripted(AUTH)+ const r = await retryPublishAfterLogin(s.publish, {+ signal: new AbortController().signal,+ timeoutMs: 10,+ now: () => t,+ sleep: async () => {+ t += 4+ }+ })+ expect(r).toEqual({ kind: 'timeout' })+ expect(s.calls()).toBe(2)+ })+ it('is cancelled by its signal before the next attempt', async () => {+ const ctl = new AbortController()+ const s = scripted(AUTH)+ const r = await retryPublishAfterLogin(s.publish, {+ signal: ctl.signal,+ sleep: async () => {+ if (s.calls() === 1) ctl.abort()+ }+ })+ expect(r).toEqual({ kind: 'cancelled' })+ expect(s.calls()).toBe(1)+ })+})++describe('startPublishRetry', () => {+ it('is single-flight per folder, outlives its caller, and clears itself when done', async () => {+ const first = startPublishRetry('/r', scripted(AUTH).publish, undefined, { sleep: () => new Promise(() => {}) })+ expect(pendingPublish('/r')).toBe(first)+ let seen: unknown+ const second = startPublishRetry('/r', scripted(OK).publish, (r) => (seen = r), instant)+ expect(pendingPublish('/r')).toBe(second)+ await expect(second.done).resolves.toEqual({ kind: 'published' })+ expect(seen).toEqual({ kind: 'published' })+ expect(pendingPublish('/r')).toBeUndefined()+ })+})diff --git a/src/renderer/lib/publishFallback.ts b/src/renderer/lib/publishFallback.tsnew file mode 100644index 000000000..fe7ae8918--- /dev/null+++ b/src/renderer/lib/publishFallback.ts@@ -0,0 +1,110 @@+import type { GitResult } from '@shared/types'++/**+ * Source Control's "Publish to GitHub" fallback when no GitHub credential is usable.+ *+ * It used to type `gh auth login && gh repo create '<name>' … --push` into a new terminal — one+ * POSIX line: Windows PowerShell 5.1 rejects `&&`, cmd.exe does not treat `'` as quoting, and the+ * `'\''` escape is wrong in every Windows shell. So the fallback is split: the terminal runs ONLY+ * the bare `gh auth login` (which every shell parses identically), and the repo create + push is+ * retried in-process through `git.publish` — whose repo name stays an argv element inside+ * git-service and never passes through a shell at all.+ */++/** The only command the fallback types: no quoting, no chaining, no user input. */+export const GH_LOGIN_COMMAND = 'gh auth login'++export type PublishOutcome =+ | { kind: 'published' }+ | { kind: 'login'; terminalCmd: typeof GH_LOGIN_COMMAND }+ | { kind: 'error'; message: string }++/** What a `git.publish` answer means for the panel. */+export function publishOutcome(r: GitResult): PublishOutcome {+ if (r.ok) return { kind: 'published' }+ if (r.needsAuth) return { kind: 'login', terminalCmd: GH_LOGIN_COMMAND }+ return { kind: 'error', message: r.message }+}++export const PUBLISH_RETRY_INTERVAL_MS = 3_000+export const PUBLISH_RETRY_TIMEOUT_MS = 5 * 60_000++export type RetryPublishResult =+ | { kind: 'published' }+ | { kind: 'error'; message: string }+ | { kind: 'timeout' }+ | { kind: 'cancelled' }++/**+ * Retry `publish` while the user signs in to gh in the terminal: every `intervalMs` until it+ * succeeds, fails for a reason other than auth, the window closes, or `signal` aborts (the panel+ * unmounted or the user cancelled). Never runs two attempts at once.+ */+export async function retryPublishAfterLogin(+ publish: () => Promise<GitResult>,+ opts: {+ signal: AbortSignal+ intervalMs?: number+ timeoutMs?: number+ now?: () => number+ sleep?: (ms: number) => Promise<void>+ }+): Promise<RetryPublishResult> {+ const intervalMs = opts.intervalMs ?? PUBLISH_RETRY_INTERVAL_MS+ const timeoutMs = opts.timeoutMs ?? PUBLISH_RETRY_TIMEOUT_MS+ const now = opts.now ?? Date.now+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))+ const deadline = now() + timeoutMs+ for (;;) {+ await sleep(intervalMs)+ if (opts.signal.aborted) return { kind: 'cancelled' }+ if (now() > deadline) return { kind: 'timeout' }+ let r: GitResult+ try {+ r = await publish()+ } catch (e) {+ return { kind: 'error', message: (e as Error)?.message || 'Publish failed.' }+ }+ if (opts.signal.aborted) return r.ok ? { kind: 'published' } : { kind: 'cancelled' }+ const o = publishOutcome(r)+ if (o.kind === 'published') return o+ if (o.kind === 'error') return o+ }+}++/**+ * One in-flight retry per repo folder, kept at module level on purpose: the user has to reach the+ * login terminal, which means closing the Source Control drawer — a retry owned by the panel would+ * die exactly when the user goes to do what it is waiting for. Bounded by the retry window.+ */+export interface PendingPublish {+ abort: () => void+ done: Promise<RetryPublishResult>+}++const pending = new Map<string, PendingPublish>()++/** The retry running for `key` (a repo folder), if any. */+export function pendingPublish(key: string): PendingPublish | undefined {+ return pending.get(key)+}++/** Start (replacing any previous one for `key`) a `retryPublishAfterLogin`, single-flight per key.+ * `onDone` runs once with the result, after the entry is cleared. */+export function startPublishRetry(+ key: string,+ publish: () => Promise<GitResult>,+ onDone?: (r: RetryPublishResult) => void,+ opts?: Omit<Parameters<typeof retryPublishAfterLogin>[1], 'signal'>+): PendingPublish {+ pending.get(key)?.abort()+ const ctl = new AbortController()+ const done = retryPublishAfterLogin(publish, { ...opts, signal: ctl.signal }).then((r) => {+ if (pending.get(key)?.done === done) pending.delete(key)+ onDone?.(r)+ return r+ })+ const entry: PendingPublish = { abort: () => ctl.abort(), done }+ pending.set(key, entry)+ return entry+}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex ad88c4c06..4caaf30b8 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -9257,6 +9257,14 @@ button.group-node__setup:disabled {.scm-error__dismiss:hover {color: var(--text-strong);}+/* Neutral variant: "waiting for GitHub sign-in" while Publish retries in-process. */+.scm-error--info {+ border-color: rgba(var(--tint-rgb), 0.18);+ background: rgba(var(--tint-rgb), 0.06);+}+.scm-error--info .scm-error__msg {+ color: var(--text-strong);+}/* Publish to GitHub picker (VS Code-style: name + private/public choice) */.pubdlg-overlay {