Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
switchdash: detect missing GitHub auth and make it take effect without a restart (CHOO-1873) (#102)
Louis Amaudruz891dd61df904
diff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.tsindex ab693706d..b4742840c 100644--- a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts@@ -23,6 +23,7 @@ import {getRemoteSwitchSetupService,type RemoteSwitchSetupService,} from '@main/core/switch-setup/remote-switch-setup';+import { GH_AUTH_STATUS_ARGS, parseGhAuthStatus } from '@shared/core/npm-registry';import { hostBlockedReason, type HostReachability } from '@shared/core/remote-hosts/reachability';import type { ConnectionState, SshHealthState } from '@shared/core/ssh/ssh';import { createRPCController } from '@shared/lib/ipc/rpc';@@ -85,27 +86,35 @@ function hostConnectionStatus(sshHost: string): HostConnectionStatus {};}-/** Matches the account line of `gh auth status` across gh versions ("account NAME" / "as NAME"). */-const GH_AUTH_ACCOUNT_RE = /Logged in to \S+ (?:account|as) (\S+)/;-/**- * Check whether `gh` is authenticated on a remote host via `gh auth status`.- * Exit 0 means authenticated; a non-zero exit (which SshExecutionContext- * throws on) means not logged in. A transport failure propagates — a dead- * connection is not evidence of a missing login.+ * Check whether `gh` is authenticated on a remote host.+ *+ * A non-zero exit (which SshExecutionContext throws on) means `gh` is missing+ * or has no login at all. A transport failure propagates — a dead connection is+ * not evidence of a missing login.+ *+ * `--json` exits zero even when the token is rejected, so an unusable+ * credential arrives as a parsed `invalid` rather than as a throw, and is+ * reported as not authenticated: a token the API refuses is no better than+ * none, and saying "authenticated" of it sends the user looking elsewhere.*/async function probeGhAuth(sshHost: string): Promise<GhAuthStatus> {const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);const ctx = new SshExecutionContext(proxy);try {- const { stdout, stderr } = await ctx.exec('gh', ['auth', 'status']);- const output = `${stdout}\n${stderr}`;- const account = GH_AUTH_ACCOUNT_RE.exec(output)?.[1] ?? null;- // gh prints "Token scopes: 'gist', 'read:org', …". Absent on very old- // versions, in which case assume the scope is there rather than nagging- // about something we cannot see.- const canReadPackages = !output.includes('Token scopes:') || output.includes('read:packages');- return { authenticated: true, account, canReadPackages };+ const { stdout } = await ctx.exec('gh', GH_AUTH_STATUS_ARGS);+ const state = parseGhAuthStatus(stdout);+ switch (state.status) {+ case 'ok':+ return { authenticated: true, account: state.login, canReadPackages: true };+ case 'missing-scope':+ return { authenticated: true, account: state.login, canReadPackages: false };+ case 'invalid':+ return { authenticated: false, account: null, canReadPackages: false };+ case 'unknown':+ // The check did not apply — do not invent a fault the host may not have.+ return { authenticated: true, account: null, canReadPackages: true };+ }} catch (error) {if (isTransportFailure(error)) throw error;return { authenticated: false, account: null, canReadPackages: false };diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.test.tsindex 4aa78067e..69b06db15 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';import type { IExecutionContext } from '@main/core/execution-context/types';-import { lacksReadPackages, NPMRC_CONTENTS } from '@shared/core/npm-registry';+import { isEnvShadowedToken, NPMRC_CONTENTS, parseGhAuthStatus } from '@shared/core/npm-registry';import { remoteNpmRegistryAuthEnv } from './npm-registry-auth';vi.mock('electron', () => ({ app: { getPath: () => '/userData' } }));@@ -35,19 +35,130 @@ function fakeCtx(handlers: {return { ctx, calls };}-describe('lacksReadPackages', () => {+function ghStatus(...entries: Record<string, unknown>[]): string {+ return JSON.stringify({ hosts: { 'github.com': entries } });+}++const KEYRING = '/home/u/.config/gh/hosts.yml';++describe('parseGhAuthStatus', () => {+ it('accepts a token carrying the scope', () => {+ const state = parseGhAuthStatus(+ ghStatus({+ state: 'success',+ active: true,+ login: 'octocat',+ tokenSource: KEYRING,+ scopes: 'gist, read:org, read:packages, repo, workflow',+ })+ );+ expect(state).toEqual({+ status: 'ok',+ login: 'octocat',+ scopes: ['gist', 'read:org', 'read:packages', 'repo', 'workflow'],+ tokenSource: KEYRING,+ });+ });+it('flags a token missing the scope', () => {- expect(lacksReadPackages("Token scopes: 'gist', 'read:org', 'repo'")).toBe(true);+ const state = parseGhAuthStatus(+ ghStatus({+ state: 'success',+ active: true,+ login: 'octocat',+ tokenSource: KEYRING,+ scopes: 'gist, read:org, repo, workflow',+ })+ );+ expect(state.status).toBe('missing-scope');+ });++ // The bug this parser replaces: the old check searched the whole of+ // `gh auth status` for the scope, so a second account that had it answered+ // for the active account that did not.+ it('judges only the active account, not whichever account has the scope', () => {+ const state = parseGhAuthStatus(+ ghStatus(+ { state: 'success', active: true, login: 'work', tokenSource: KEYRING, scopes: 'repo' },+ {+ state: 'success',+ active: false,+ login: 'personal',+ tokenSource: KEYRING,+ scopes: 'repo, read:packages',+ }+ )+ );+ expect(state.status).toBe('missing-scope');+ });++ // The state a stale GH_TOKEN produces: the env token is active and rejected,+ // while the keyring account below it is healthy and has the scope.+ it('reports an unusable active token even when another account is fine', () => {+ const state = parseGhAuthStatus(+ ghStatus(+ {+ state: 'error',+ active: true,+ login: '',+ tokenSource: 'GH_TOKEN',+ error: 'non-200 OK status code: 401 Unauthorized',+ },+ {+ state: 'success',+ active: false,+ login: 'octocat',+ tokenSource: KEYRING,+ scopes: 'repo, read:packages',+ }+ )+ );+ expect(state).toMatchObject({ status: 'invalid', tokenSource: 'GH_TOKEN' });+ expect(isEnvShadowedToken(state)).toBe(true);+ });++ it('recognises an environment token that is otherwise healthy', () => {+ const state = parseGhAuthStatus(+ ghStatus({+ state: 'success',+ active: true,+ login: 'octocat',+ tokenSource: 'GH_TOKEN',+ scopes: 'repo, read:packages',+ })+ );+ expect(state.status).toBe('ok');+ // Healthy today, but it outlives the next `gh auth login` — worth saying.+ expect(isEnvShadowedToken(state)).toBe(true);+ });++ it('does not treat the keyring as a shadowing token', () => {+ const state = parseGhAuthStatus(+ ghStatus({+ state: 'success',+ active: true,+ login: 'octocat',+ tokenSource: KEYRING,+ scopes: 'read:packages',+ })+ );+ expect(isEnvShadowedToken(state)).toBe(false);});- it('accepts a token carrying it', () => {- expect(lacksReadPackages("Token scopes: 'read:packages', 'repo'")).toBe(false);+ // Guessing wrong must not send someone chasing a scope they already have,+ // nor block setup on a check that did not apply.+ it.each([+ ['unparseable output', 'gh: unknown flag --json'],+ ['no hosts', JSON.stringify({ hosts: {} })],+ ])('returns unknown for %s', (_label, stdout) => {+ expect(parseGhAuthStatus(stdout)).toEqual({ status: 'unknown' });});- // The output is human-readable and may change. Guessing wrong must not- // produce a warning that sends someone chasing a scope they already have.- it('says nothing when there is no scope line', () => {- expect(lacksReadPackages('not logged in')).toBe(false);+ it('returns unknown when the scope field is absent', () => {+ const state = parseGhAuthStatus(+ ghStatus({ state: 'success', active: true, login: 'octocat', tokenSource: KEYRING })+ );+ expect(state).toEqual({ status: 'unknown' });});});@@ -55,7 +166,16 @@ describe('remoteNpmRegistryAuthEnv', () => {it('writes the npmrc on the remote host and returns the env pointing at it', async () => {const { ctx, calls } = fakeCtx({token: async () => ({ stdout: 'ghp_remote\n', stderr: '' }),- status: async () => ({ stdout: "Token scopes: 'read:packages'", stderr: '' }),+ status: async () => ({+ stdout: ghStatus({+ state: 'success',+ active: true,+ login: 'octocat',+ tokenSource: KEYRING,+ scopes: 'repo, read:packages',+ }),+ stderr: '',+ }),});const env = await remoteNpmRegistryAuthEnv(ctx, '/home/ubuntu/repo');diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.tsindex c10228111..761e3b5db 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.ts@@ -5,14 +5,20 @@ import { promisify } from 'node:util';import { app } from 'electron';import type { IExecutionContext } from '@main/core/execution-context/types';import { GH_EXECUTABLE, getGithubTokenFromGhCli } from '@main/core/updates/github-token';+import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import { quoteShellArg } from '@main/utils/shellEscape';import {- lacksReadPackages,+ GH_AUTH_STATUS_ARGS,+ type GhAuthState,+ isEnvShadowedToken,NPMRC_CONTENTS,npmRegistryEnv,+ parseGhAuthStatus,READ_PACKAGES_FIX,+ READ_PACKAGES_SCOPE,} from '@shared/core/npm-registry';+import { switchToolsUnavailableEvent } from '@shared/events/switchSetupEvents';const execFileAsync = promisify(execFile);@@ -31,6 +37,66 @@ const MISSING_SCOPE_DETAIL ='gh auth login does not request read:packages, so the registry will refuse ' +'with 403 and the session will start without its MCP tools';+/**+ * Report what `gh` will do with its current credentials.+ *+ * A shadowed token is called out separately because the remedy differs: the+ * user has usually just authenticated, and being told to authenticate again+ * would send them round the loop that produced the state.+ */+function warnAboutGhAuth(state: GhAuthState, host: string): void {+ if (isEnvShadowedToken(state)) {+ log.warn('npmRegistryAuth: an environment token is shadowing the gh login', {+ event: 'npm_registry_auth_env_shadowed',+ host,+ tokenSource: state.status === 'unknown' ? 'unknown' : state.tokenSource,+ detail:+ 'gh prefers GH_TOKEN/GITHUB_TOKEN over the keyring, so re-running gh auth ' ++ 'login will not change which token is used until that variable is unset',+ });+ }+ if (state.status === 'missing-scope') {+ log.warn('npmRegistryAuth: the GitHub token cannot read packages', {+ event: 'npm_registry_auth_missing_scope',+ host,+ account: state.login,+ scopes: state.scopes.join(', '),+ fix: READ_PACKAGES_FIX,+ detail: MISSING_SCOPE_DETAIL,+ });+ } else if (state.status === 'invalid') {+ log.warn('npmRegistryAuth: the active GitHub token is not usable', {+ event: 'npm_registry_auth_invalid_token',+ host,+ tokenSource: state.tokenSource,+ detail: state.detail,+ });+ }+}++/**+ * Tell the user, not just the log, when the session will come up without tools.+ *+ * Only for sessions on this machine: a remote host's state belongs on that+ * host's setup page, where it is already reported, and a toast cannot say which+ * host it meant.+ */+function announceUnusableAuth(state: GhAuthState): void {+ if (state.status === 'missing-scope') {+ events.emit(switchToolsUnavailableEvent, {+ reason: 'missing-scope',+ detail: `The GitHub token is missing the ${READ_PACKAGES_SCOPE} scope.`,+ });+ } else if (state.status === 'invalid') {+ events.emit(switchToolsUnavailableEvent, {+ reason: isEnvShadowedToken(state) ? 'env-shadowed' : 'invalid-token',+ detail: isEnvShadowedToken(state)+ ? `A ${state.tokenSource} environment variable is overriding your gh login, and it is not usable.`+ : state.detail,+ });+ }+}+function localNpmrcPath(): string {return join(app.getPath('userData'), 'npm', 'npmrc');}@@ -50,20 +116,20 @@ export async function npmRegistryAuthEnv(): Promise<Record<string, string>> {event: 'npm_registry_auth_missing_token',hint: 'run `gh auth login`; a private package reads as 404 without it',});+ events.emit(switchToolsUnavailableEvent, {+ reason: 'not-authenticated',+ detail: 'This machine is not authenticated to GitHub.',+ });return {};}try {- const { stdout, stderr } = await execFileAsync(GH_EXECUTABLE, ['auth', 'status'], {+ const { stdout } = await execFileAsync(GH_EXECUTABLE, GH_AUTH_STATUS_ARGS, {timeout: 10_000,});- if (lacksReadPackages(`${stdout}${stderr}`)) {- log.warn('npmRegistryAuth: the GitHub token cannot read packages', {- event: 'npm_registry_auth_missing_scope',- fix: READ_PACKAGES_FIX,- detail: MISSING_SCOPE_DETAIL,- });- }+ const state = parseGhAuthStatus(stdout);+ warnAboutGhAuth(state, 'this machine');+ announceUnusableAuth(state);} catch {// Never fatal — a diagnostic, not a gate.}@@ -125,14 +191,8 @@ export async function remoteNpmRegistryAuthEnv(}try {- const { stdout, stderr } = await ctx.exec('gh', ['auth', 'status'], { timeout: 15_000 });- if (lacksReadPackages(`${stdout}${stderr}`)) {- log.warn('npmRegistryAuth: the remote GitHub token cannot read packages', {- event: 'npm_registry_auth_missing_scope',- fix: READ_PACKAGES_FIX,- detail: MISSING_SCOPE_DETAIL,- });- }+ const { stdout } = await ctx.exec('gh', GH_AUTH_STATUS_ARGS, { timeout: 15_000 });+ warnAboutGhAuth(parseGhAuthStatus(stdout), 'the remote host');} catch {// Never fatal — a diagnostic, not a gate.}diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/controller.tsindex 3cb138943..664dadd60 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/controller.ts@@ -1,11 +1,18 @@import { hostReachabilityService } from '@main/core/remote-hosts/production-host-reachability';import { log } from '@main/lib/logger';import { createRPCController } from '@shared/lib/ipc/rpc';+import { type LocalGhAuthStatus, probeLocalGhAuth, startLocalGhAuth } from './local-gh-auth';import { getRemoteSwitchSetupService } from './remote-switch-setup';import { switchSetupService } from './switch-setup-service';export const switchSetupController = createRPCController({listOnboardable: () => switchSetupService.listOnboardable(),++ /** Whether this machine can fetch the MCP runtime from GitHub Packages. */+ getLocalGhAuth: (): Promise<LocalGhAuthStatus> => probeLocalGhAuth(),++ /** Interactive `gh` login/refresh on this machine; returns a PTY session id. */+ startLocalGhAuth: (): Promise<{ sessionId: string }> => startLocalGhAuth(),/*** Agent types installed on a remote host. An unreachable host has no* answerable list, so return none rather than throwing: this is a query thatdiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/local-gh-auth.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/local-gh-auth.test.tsnew file mode 100644index 000000000..ca7ae9810--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/local-gh-auth.test.ts@@ -0,0 +1,156 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const execFileMock = vi.hoisted(() => vi.fn());+const spawnLocalPty = vi.hoisted(() =>+ vi.fn((_options: { args: string[]; env: Record<string, string> }) => ({ id: 'pty' }))+);+const register = vi.hoisted(() => vi.fn());++vi.mock('node:child_process', () => ({ execFile: execFileMock }));+vi.mock('node:util', () => ({ promisify: () => execFileMock }));+vi.mock('@main/core/pty/local-pty', () => ({ spawnLocalPty }));+vi.mock('@main/core/pty/pty-session-registry', () => ({ ptySessionRegistry: { register } }));+vi.mock('@main/core/updates/github-token', () => ({ GH_EXECUTABLE: 'gh' }));+vi.mock('@main/lib/logger', () => ({+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));++const { probeLocalGhAuth, startLocalGhAuth } = await import('./local-gh-auth');++function ghStatus(...entries: Record<string, unknown>[]): string {+ return JSON.stringify({ hosts: { 'github.com': entries } });+}++const KEYRING = '/home/u/.config/gh/hosts.yml';++const HEALTHY = ghStatus({+ state: 'success',+ active: true,+ login: 'octocat',+ tokenSource: KEYRING,+ scopes: 'repo, read:packages',+});++beforeEach(() => {+ execFileMock.mockReset();+ spawnLocalPty.mockClear();+ register.mockClear();+});++describe('probeLocalGhAuth', () => {+ it('reports a usable login', async () => {+ execFileMock.mockResolvedValue({ stdout: HEALTHY, stderr: '' });+ expect(await probeLocalGhAuth()).toEqual({+ ghInstalled: true,+ authenticated: true,+ canReadPackages: true,+ account: 'octocat',+ envShadowed: false,+ detail: null,+ });+ });++ it('reports a login that cannot read packages', async () => {+ execFileMock.mockResolvedValue({+ stdout: ghStatus({+ state: 'success',+ active: true,+ login: 'octocat',+ tokenSource: KEYRING,+ scopes: 'repo',+ }),+ stderr: '',+ });+ const status = await probeLocalGhAuth();+ expect(status).toMatchObject({ authenticated: true, canReadPackages: false });+ expect(status.detail).toContain('read:packages');+ });++ // A token the API rejects is no better than none, and calling it+ // authenticated sends the user looking in the wrong place.+ it('reports a rejected token as not authenticated, and names the shadowing', async () => {+ execFileMock.mockResolvedValue({+ stdout: ghStatus({+ state: 'error',+ active: true,+ login: '',+ tokenSource: 'GH_TOKEN',+ error: '401 Unauthorized',+ }),+ stderr: '',+ });+ expect(await probeLocalGhAuth()).toMatchObject({+ authenticated: false,+ envShadowed: true,+ detail: '401 Unauthorized',+ });+ });++ it('reports a missing gh binary distinctly from a missing login', async () => {+ execFileMock.mockRejectedValue(Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' }));+ expect(await probeLocalGhAuth()).toMatchObject({+ ghInstalled: false,+ authenticated: false,+ });+ });++ it('treats a non-zero exit as no login', async () => {+ execFileMock.mockRejectedValue(new Error('exit 1'));+ expect(await probeLocalGhAuth()).toMatchObject({+ ghInstalled: true,+ authenticated: false,+ detail: 'Not logged in to GitHub.',+ });+ });++ // Reporting a fault we cannot see would block setup for a working install.+ it('assumes ready when the output cannot be understood', async () => {+ execFileMock.mockResolvedValue({ stdout: 'gh: unknown flag --json', stderr: '' });+ expect(await probeLocalGhAuth()).toMatchObject({+ ghInstalled: true,+ authenticated: true,+ canReadPackages: true,+ });+ });+});++describe('startLocalGhAuth', () => {+ it('refreshes when already logged in, asking for the scope', async () => {+ execFileMock.mockResolvedValue({ stdout: HEALTHY, stderr: '' });+ await startLocalGhAuth();+ const { args } = spawnLocalPty.mock.calls[0][0];+ expect(args.slice(0, 2)).toEqual(['auth', 'refresh']);+ expect(args).toContain('read:packages');+ });++ it('logs in when there is no login, asking for the scope', async () => {+ execFileMock.mockRejectedValue(new Error('exit 1'));+ await startLocalGhAuth();+ const { args } = spawnLocalPty.mock.calls[0][0];+ expect(args.slice(0, 2)).toEqual(['auth', 'login']);+ expect(args).toContain('read:packages');+ });++ // gh prefers these over the keyring, so `gh auth refresh` would act on the+ // environment token — the very thing the user is trying to get past.+ it('runs without the environment tokens that would shadow the keyring', async () => {+ execFileMock.mockResolvedValue({ stdout: HEALTHY, stderr: '' });+ process.env.GH_TOKEN = 'stale';+ process.env.GITHUB_TOKEN = 'stale';+ try {+ await startLocalGhAuth();+ } finally {+ delete process.env.GH_TOKEN;+ delete process.env.GITHUB_TOKEN;+ }+ const { env } = spawnLocalPty.mock.calls[0][0];+ expect(env.GH_TOKEN).toBeUndefined();+ expect(env.GITHUB_TOKEN).toBeUndefined();+ });++ it('refuses when gh is not installed, naming where to get it', async () => {+ execFileMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));+ await expect(startLocalGhAuth()).rejects.toThrow(/cli\.github\.com/);+ expect(spawnLocalPty).not.toHaveBeenCalled();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/local-gh-auth.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/local-gh-auth.tsnew file mode 100644index 000000000..7647d5ffa--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/local-gh-auth.ts@@ -0,0 +1,195 @@+import { execFile } from 'node:child_process';+import { homedir } from 'node:os';+import { promisify } from 'node:util';+import { spawnLocalPty } from '@main/core/pty/local-pty';+import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';+import { GH_EXECUTABLE } from '@main/core/updates/github-token';+import { log } from '@main/lib/logger';+import {+ GH_AUTH_STATUS_ARGS,+ GH_HOST,+ type GhAuthState,+ isEnvShadowedToken,+ READ_PACKAGES_SCOPE,+} from '@shared/core/npm-registry';+import { parseGhAuthStatus } from '@shared/core/npm-registry';++const execFileAsync = promisify(execFile);++/**+ * Whether this machine can fetch the Switch MCP runtime from GitHub Packages.+ *+ * The remote-hosts page has had this for a while; locally there was nothing, so+ * the same misconfiguration produced a session that looked healthy and silently+ * had no Switch tools.+ */+export type LocalGhAuthStatus = {+ ghInstalled: boolean;+ authenticated: boolean;+ account: string | null;+ canReadPackages: boolean;+ /**+ * An environment token is being used instead of the keyring.+ *+ * Worth its own field rather than folding into the others: it is the one+ * state that re-authenticating does not fix, so the UI has to say something+ * different. `gh` prefers `GH_TOKEN`/`GITHUB_TOKEN`, and switchdash inherits+ * whatever the user's shell exported.+ */+ envShadowed: boolean;+ /** Why the credential is unusable, when it is. */+ detail: string | null;+};++const READY: Pick<LocalGhAuthStatus, 'ghInstalled' | 'authenticated' | 'canReadPackages'> = {+ ghInstalled: true,+ authenticated: true,+ canReadPackages: true,+};++function statusFrom(state: GhAuthState): LocalGhAuthStatus {+ const envShadowed = isEnvShadowedToken(state);+ switch (state.status) {+ case 'ok':+ return { ...READY, account: state.login, envShadowed, detail: null };+ case 'missing-scope':+ return {+ ...READY,+ canReadPackages: false,+ account: state.login,+ envShadowed,+ detail: `The GitHub token is missing the ${READ_PACKAGES_SCOPE} scope.`,+ };+ case 'invalid':+ return {+ ghInstalled: true,+ authenticated: false,+ canReadPackages: false,+ account: null,+ envShadowed,+ detail: state.detail,+ };+ case 'unknown':+ // The check did not apply. Claiming a fault we cannot see would block+ // setup for someone whose install works.+ return { ...READY, account: null, envShadowed: false, detail: null };+ }+}++/** What `gh` on this machine will do, in the shape the setup UI renders. */+export async function probeLocalGhAuth(): Promise<LocalGhAuthStatus> {+ try {+ const { stdout } = await execFileAsync(GH_EXECUTABLE, GH_AUTH_STATUS_ARGS, {+ timeout: 10_000,+ });+ return statusFrom(parseGhAuthStatus(stdout));+ } catch (error) {+ if ((error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') {+ return {+ ghInstalled: false,+ authenticated: false,+ canReadPackages: false,+ account: null,+ envShadowed: false,+ detail: 'The GitHub CLI (gh) is not installed.',+ };+ }+ // `gh auth status --json` exits zero even for a rejected token, so a+ // non-zero exit here means no login at all rather than a bad one. Older gh+ // versions that reject `--json` also land here; they are reported the same+ // way, and the authenticate flow that follows is correct for both.+ const stdout = (error as { stdout?: string } | undefined)?.stdout;+ if (stdout) {+ const state = parseGhAuthStatus(stdout);+ if (state.status !== 'unknown') return statusFrom(state);+ }+ return {+ ghInstalled: true,+ authenticated: false,+ canReadPackages: false,+ account: null,+ envShadowed: false,+ detail: 'Not logged in to GitHub.',+ };+ }+}++/**+ * The environment for the interactive login.+ *+ * `GH_TOKEN`/`GITHUB_TOKEN` are removed so the flow acts on the keyring: `gh`+ * prefers them, and `gh auth refresh` against an environment token fails rather+ * than adding the scope. Removing them here only affects this one child — a+ * user who genuinely authenticates by environment variable still has it, and+ * `envShadowed` is how they are told it is what the runtime will use.+ */+function ghAuthEnv(): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [key, value] of Object.entries(process.env)) {+ if (value === undefined) continue;+ if (key === 'GH_TOKEN' || key === 'GITHUB_TOKEN') continue;+ env[key] = value;+ }+ return env;+}++/**+ * Start an interactive `gh` device-flow login on this machine, in a PTY the+ * renderer attaches a live terminal to.+ *+ * `read:packages` is requested explicitly because `gh auth login` does not ask+ * for it — its defaults are `gist`, `read:org`, `repo` and `workflow`. Asking+ * during the one interactive login the user already performs is the only point+ * where it costs nothing; every other route ends in `gh auth refresh` on a+ * machine they thought was set up.+ *+ * Refresh when already logged in, login when not: `gh auth login` on an+ * authenticated machine stops to ask whether you meant to re-authenticate,+ * which is a confusing thing to meet when all you needed was a scope. The+ * branch is decided here rather than in a shell so there is no quoting to get+ * wrong and nothing that assumes a POSIX shell exists.+ */+export async function startLocalGhAuth(): Promise<{ sessionId: string }> {+ const status = await probeLocalGhAuth();+ if (!status.ghInstalled) {+ throw new Error(+ 'The GitHub CLI (gh) is not installed. Install it from https://cli.github.com and try again.'+ );+ }++ const args = status.authenticated+ ? ['auth', 'refresh', '--hostname', GH_HOST, '--scopes', READ_PACKAGES_SCOPE]+ : [+ 'auth',+ 'login',+ '--hostname',+ GH_HOST,+ '--git-protocol',+ 'https',+ '--web',+ '--scopes',+ READ_PACKAGES_SCOPE,+ ];++ const sessionId = `gh-auth-local:${crypto.randomUUID()}`;+ log.info('startLocalGhAuth: starting interactive gh auth', {+ event: 'local_gh_auth_start',+ mode: status.authenticated ? 'refresh' : 'login',+ sessionId,+ });++ const pty = spawnLocalPty({+ id: sessionId,+ command: GH_EXECUTABLE,+ args,+ cwd: homedir(),+ env: ghAuthEnv(),+ cols: 80,+ rows: 24,+ });++ ptySessionRegistry.register(sessionId, pty, {+ metadata: { title: 'gh auth login', isRemote: false },+ });+ return { sessionId };+}diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.tsindex 527d500c5..85e6f01b9 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.ts@@ -6,8 +6,11 @@ const mocks = vi.hoisted(() => ({getPlugin: vi.fn(),listPlugins: vi.fn(),readFile: vi.fn(),+ probeLocalGhAuth: vi.fn(),}));+vi.mock('./local-gh-auth', () => ({ probeLocalGhAuth: mocks.probeLocalGhAuth }));+vi.mock('@main/core/execution-context/local-execution-context', () => ({LocalExecutionContext: class {exec = mocks.exec;@@ -116,6 +119,14 @@ beforeEach(() => {vi.clearAllMocks();mocks.resolveCommandPath.mockResolvedValue('/usr/bin/claude');mocks.getPlugin.mockReturnValue(CLI_AGENT);+ mocks.probeLocalGhAuth.mockResolvedValue({+ ghInstalled: true,+ authenticated: true,+ canReadPackages: true,+ account: 'octocat',+ envShadowed: false,+ detail: null,+ });});describe('switchSetupService.getStatus', () => {@@ -185,6 +196,30 @@ describe('switchSetupService.listOnboardable', () => {expect(onboardable).toEqual([]);});++ // An installed plugin still resolves its MCP server from a private registry+ // at session start. Offering the agent type on the strength of the install+ // alone onboards an agent that comes up with no Switch tools.+ it.each([+ ['gh is not installed', { ghInstalled: false, authenticated: false, canReadPackages: false }],+ ['there is no login', { ghInstalled: true, authenticated: false, canReadPackages: false }],+ [+ 'the token cannot read packages',+ { ghInstalled: true, authenticated: true, canReadPackages: false },+ ],+ ])('offers nothing when %s, even with the connector installed', async (_label, gh) => {+ mocks.listPlugins.mockReturnValue([CLI_AGENT, NONE_AGENT]);+ mocks.exec.mockImplementation(execImpl('0.1.0'));+ mocks.readFile.mockImplementation(readFileImpl('0.1.0', '0.1.0'));+ mocks.probeLocalGhAuth.mockResolvedValue({+ ...gh,+ account: null,+ envShadowed: false,+ detail: 'nope',+ });++ expect(await switchSetupService.listOnboardable()).toEqual([]);+ });});describe('switchSetupService.checkForUpdates', () => {diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.tsindex 8c838ef63..9e8e35f5a 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts@@ -4,7 +4,9 @@ import { resolveCommandPath } from '@switchdash/core/deps/runtime';import semver from 'semver';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import { log } from '@main/lib/logger';+import { READ_PACKAGES_SCOPE } from '@shared/core/npm-registry';import { getPlugin, listPlugins } from '../providers/plugin-registry';+import { probeLocalGhAuth } from './local-gh-auth';/** Status of an agent type's Switch connector plugin. */export type SwitchSetupStatus = {@@ -42,6 +44,40 @@ export type SwitchSetupResult = { success: boolean; message?: string };const EXEC_TIMEOUT_MS = 120_000;+/** Failures that mean the CLI could not read the private marketplace repo. */+const NOT_FOUND_RE = /\b(404|403|not found|could not resolve|authentication|permission denied)\b/i;++/**+ * Attach a cause to an install failure.+ *+ * The marketplace lives in a private repo, so an unauthenticated CLI is told+ * the repo does not exist. Passed through untouched — as it was — the user+ * reads "404" and has no way to know it is about their GitHub login, or gets+ * "Install failed." with nothing at all when the CLI wrote no stderr.+ *+ * The GitHub state is only consulted once something has already failed: it+ * costs a subprocess, and a healthy install should not pay for it.+ */+async function describeInstallFailure(raw: string): Promise<string> {+ const message = raw || 'Install failed.';+ if (raw && !NOT_FOUND_RE.test(raw)) return message;++ const gh = await probeLocalGhAuth();+ if (!gh.ghInstalled) {+ return `${message}\n\nThe Switch plugin is published to a private GitHub repository, and the GitHub CLI (gh) is not installed on this machine. Install it from https://cli.github.com, then authenticate.`;+ }+ if (!gh.authenticated) {+ return `${message}\n\nThe Switch plugin is published to a private GitHub repository and this machine is not authenticated to GitHub${gh.detail ? ` (${gh.detail})` : ''}. Authenticate from Switch setup and try again.`;+ }+ if (!gh.canReadPackages) {+ return `${message}\n\nThe GitHub token is missing the ${READ_PACKAGES_SCOPE} scope, which is required to read the private Switch packages. Re-authenticate from Switch setup and try again.`;+ }+ if (gh.envShadowed) {+ return `${message}\n\nGitHub access is coming from a GH_TOKEN/GITHUB_TOKEN environment variable rather than your gh login, and that token cannot reach the private Switch repository. Unset it, or give it the ${READ_PACKAGES_SCOPE} scope.`;+ }+ return message;+}+type RunResult = { code: number; stdout: string; stderr: string };function unsupported(agentId: string): SwitchSetupStatus {@@ -237,7 +273,29 @@ class SwitchSetupService {* descriptor) AND with their connector plugin already installed. Drives the* onboarding agent-type picker, which only offers ready-to-use types.*/+ /**+ * Agent types that can actually be onboarded on this machine.+ *+ * An installed plugin is not sufficient. The plugin resolves its MCP server+ * from a private registry at session start, so without GitHub access the+ * agent onboards, reports itself installed, and then runs with no Switch+ * tools — which is what "installed" appeared to promise. Availability is+ * withheld until the credential can actually fetch it, matching how a remote+ * host reports readiness.+ */async listOnboardable(): Promise<{ agentId: string }[]> {+ const gh = await probeLocalGhAuth();+ if (!gh.ghInstalled || !gh.authenticated || !gh.canReadPackages) {+ log.warn('switch-setup: no agent type is onboardable — GitHub access is not usable', {+ event: 'switch_setup_onboarding_blocked_by_github',+ ghInstalled: gh.ghInstalled,+ authenticated: gh.authenticated,+ canReadPackages: gh.canReadPackages,+ envShadowed: gh.envShadowed,+ });+ return [];+ }+const onboardable: { agentId: string }[] = [];for (const plugin of listPlugins()) {if (plugin.capabilities.switchSetup.kind !== 'cli') continue;@@ -285,12 +343,12 @@ class SwitchSetupService {try {await this.ensureMarketplace(bin, descriptor.marketplaceName, descriptor.marketplaceSource);} catch (err) {- return { success: false, message: `Could not add marketplace: ${String(err)}` };+ return { success: false, message: await describeInstallFailure(String(err)) };}const res = await this.run(bin, ['plugin', 'install', ref, '-s', descriptor.scope]);return res.code === 0? { success: true }- : { success: false, message: res.stderr.trim() || 'Install failed.' };+ : { success: false, message: await describeInstallFailure(res.stderr.trim()) };}async update(agentId: string): Promise<SwitchSetupResult> {diff --git a/dash/apps/switchdash-desktop/src/main/core/updates/update-service.ts b/dash/apps/switchdash-desktop/src/main/core/updates/update-service.tsindex ff7b6af46..40be6633f 100644--- a/dash/apps/switchdash-desktop/src/main/core/updates/update-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/updates/update-service.ts@@ -7,7 +7,12 @@ import _electronUpdater, {import { resolveAppVersion } from '@main/core/app/utils';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';-import { IS_CANARY, UPDATE_CHANNEL } from '@shared/app-identity';+import {+ IS_CANARY,+ RELEASE_REPO_NAME,+ RELEASE_REPO_OWNER,+ UPDATE_CHANNEL,+} from '@shared/app-identity';import {updateAuthRequiredEvent,updateAvailableEvent,@@ -213,10 +218,20 @@ class UpdateService implements IInitializable, IDisposable {log.info('Skipping update check: no GitHub token from gh CLI (run `gh auth login`)');return null;}- // electron-updater selects its authenticated GitHub provider (api.github.com)- // from GH_TOKEN; without it, a private repo falls back to the public- // releases.atom feed and 404s. The header alone is not enough.- process.env.GH_TOKEN = token;+ // A private repo needs electron-updater's authenticated provider+ // (api.github.com); the public releases.atom feed 404s and the auth header+ // alone does not select it. The token goes through setFeedURL rather than+ // GH_TOKEN: the environment is inherited by every child process switchdash+ // spawns — including `gh` itself, which prefers GH_TOKEN over the keyring —+ // so a token left there outlives the login it came from and shadows the+ // next one until the app restarts.+ autoUpdater.setFeedURL({+ provider: 'github',+ owner: RELEASE_REPO_OWNER,+ repo: RELEASE_REPO_NAME,+ private: true,+ token,+ });autoUpdater.requestHeaders = {'Cache-Control': 'no-cache',authorization: `token ${token}`,diff --git a/dash/apps/switchdash-desktop/src/renderer/App.tsx b/dash/apps/switchdash-desktop/src/renderer/App.tsxindex 02502b5d1..ec96c4de7 100644--- a/dash/apps/switchdash-desktop/src/renderer/App.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/App.tsx@@ -2,6 +2,7 @@ import { QueryClientProvider } from '@tanstack/react-query';import { AppMenuEvents } from './app/app-menu-events';import { Workspace } from './app/workspace';import { SessionDeeplinkListener } from './features/switch-rooms/session-deeplink-listener';+import { SwitchToolsUnavailableListener } from './features/switch-rooms/switch-tools-unavailable-listener';import { WorkspaceLayoutContextProvider } from './lib/layout/layout-provider';import { WorkspaceViewProvider } from './lib/layout/provider';import { ModalRenderer } from './lib/modal/modal-renderer';@@ -19,6 +20,7 @@ function AppContent() {<WorkspaceViewProvider><AppMenuEvents /><SessionDeeplinkListener />+ <SwitchToolsUnavailableListener /><RightSidebarProvider><ThemeProvider><ModalRenderer />diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsxindex dce991809..8b8c9263a 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx@@ -1,5 +1,6 @@import { CircleAlert } from 'lucide-react';import { useEffect, useMemo } from 'react';+import { useLocalGhAuth } from '@renderer/features/settings/agents-page/LocalGhAuthRow';import { AgentIcon } from '@renderer/lib/components/agent-icon';import { useAgents } from '@renderer/lib/stores/use-agents';import { useOnboardableAgentTypes } from '@renderer/lib/stores/use-switch-setup';@@ -31,6 +32,9 @@ export function AgentTypePicker({}) {const { data: onboardable, isPending } = useOnboardableAgentTypes(sshHost);const { data: agents } = useAgents();+ const { data: ghAuth } = useLocalGhAuth();+ const githubBlocked =+ !!ghAuth && !(ghAuth.ghInstalled && ghAuth.authenticated && ghAuth.canReadPackages);const options = useMemo(() => {const byId = new Map((agents ?? []).map((a) => [a.id, a]));@@ -52,7 +56,17 @@ export function AgentTypePicker({but availability is per-host — the connector may well be installedlocally and simply missing on the machine being targeted. */}<span>- {sshHost ? (+ {/* The plugin may be installed and the agent still unusable, so the+ GitHub reason has to be given ahead of the install advice —+ otherwise it sends the user to install something they already+ have. */}+ {!sshHost && githubBlocked ? (+ <>+ This computer cannot reach the private GitHub packages the Switch connector needs+ {ghAuth?.detail ? ` — ${ghAuth.detail}` : '.'} Authenticate under Settings →+ Agents → Switch setup, then try again.+ </>+ ) : sshHost ? (<>No agent type is set up for Switch on <span className="font-medium">{sshHost}</span>.Install an agent's Switch connector on that host in Settings → Remote hostsdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/LocalGhAuthPanel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/LocalGhAuthPanel.tsxnew file mode 100644index 000000000..33dd224e6--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/LocalGhAuthPanel.tsx@@ -0,0 +1,131 @@+import { useEffect, useRef, useState } from 'react';+import { events, rpc } from '@renderer/lib/ipc';+import { FrontendPty } from '@renderer/lib/pty/pty';+import { PtyPane } from '@renderer/lib/pty/pty-pane';+import { Button } from '@renderer/lib/ui/button';+import { Spinner } from '@renderer/lib/ui/spinner';+import { ptyExitChannel } from '@shared/core/pty/ptyEvents';++type Props = {+ /** Called when the user dismisses the panel (cancel or done). */+ onDone: () => void;+};++/**+ * Interactive `gh` device-flow login for this machine, rendered as a live+ * terminal INLINE on the agents settings page.+ *+ * The local counterpart of the remote-hosts GhAuthPanel, and inline for the+ * same reason: switchdash's terminal input path is disabled whenever a+ * `[role="dialog"]` is present, so a terminal in a modal can never receive+ * keystrokes.+ */+export function LocalGhAuthPanel({ onDone }: Props) {+ const [pty, setPty] = useState<FrontendPty | null>(null);+ const [sessionId, setSessionId] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [exitCode, setExitCode] = useState<number | null | undefined>(undefined);++ const ptyRef = useRef<FrontendPty | null>(null);+ const sessionIdRef = useRef<string | null>(null);+ const paneRef = useRef<{ focus: () => void } | null>(null);++ useEffect(() => {+ let cancelled = false;+ let offExit: (() => void) | undefined;++ void (async () => {+ try {+ const { sessionId: sid } = await rpc.switchSetup.startLocalGhAuth();+ if (cancelled) {+ void rpc.pty.kill(sid);+ return;+ }+ sessionIdRef.current = sid;+ setSessionId(sid);++ const frontend = new FrontendPty(sid);+ await frontend.connect();+ if (cancelled) {+ frontend.dispose();+ void rpc.pty.kill(sid);+ return;+ }+ ptyRef.current = frontend;+ setPty(frontend);++ offExit = events.on(+ ptyExitChannel,+ (info: { exitCode: number; signal?: number }) => {+ setExitCode(info.exitCode ?? null);+ },+ sid+ );+ } catch (e) {+ if (!cancelled) setError(e instanceof Error ? e.message : String(e));+ }+ })();++ return () => {+ cancelled = true;+ offExit?.();+ const sid = sessionIdRef.current;+ if (sid) void rpc.pty.kill(sid);+ ptyRef.current?.dispose();+ };+ }, []);++ useEffect(() => {+ if (!pty) return;+ const id = requestAnimationFrame(() => paneRef.current?.focus());+ return () => cancelAnimationFrame(id);+ }, [pty]);++ const exited = exitCode !== undefined;+ const succeeded = exitCode === 0;++ return (+ <div className="flex flex-col gap-3 rounded-md border border-border p-3">+ <div className="flex items-center justify-between gap-2">+ <h5 className="text-sm font-medium">Authenticate GitHub CLI on this machine</h5>+ <Button size="sm" variant="outline" onClick={onDone}>+ {succeeded ? 'Close' : 'Cancel'}+ </Button>+ </div>++ <p className="text-xs text-foreground-muted">+ gh will print a one-time code and a verification URL below. Click the URL (or open{' '}+ <span className="font-mono">github.com/login/device</span>) in your browser, enter the code,+ and authorize.+ </p>++ {error ? (+ <p className="text-destructive text-xs">{error}</p>+ ) : !pty || !sessionId ? (+ <div className="flex items-center gap-2 text-sm text-foreground-muted">+ <Spinner /> Starting gh auth…+ </div>+ ) : (+ <div className="h-72 overflow-hidden rounded-md border border-border">+ <PtyPane+ ref={paneRef}+ sessionId={sessionId}+ pty={pty}+ locationId=""+ className="h-full w-full"+ />+ </div>+ )}++ {exited &&+ (succeeded ? (+ <p className="text-xs text-green-500">Authenticated successfully.</p>+ ) : (+ <p className="text-destructive text-xs">+ gh auth exited{exitCode == null ? '' : ` with code ${exitCode}`} without completing. You+ can close and try again.+ </p>+ ))}+ </div>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/LocalGhAuthRow.tsx b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/LocalGhAuthRow.tsxnew file mode 100644index 000000000..08254b6bc--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/LocalGhAuthRow.tsx@@ -0,0 +1,99 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { AlertTriangle, Check, Loader2 } from 'lucide-react';+import { useState } from 'react';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { LocalGhAuthPanel } from './LocalGhAuthPanel';++export const localGhAuthQueryKey = ['switchSetup', 'localGhAuth'] as const;++export function useLocalGhAuth() {+ return useQuery({+ queryKey: localGhAuthQueryKey,+ queryFn: () => rpc.switchSetup.getLocalGhAuth(),+ staleTime: 30_000,+ });+}++/**+ * GitHub access for the Switch plugin, on this machine.+ *+ * Remote hosts have had this row since the scope became a requirement; locally+ * there was nothing, so the same misconfiguration produced a plugin that would+ * not install and sessions that came up silently without their Switch tools.+ */+export function LocalGhAuthRow() {+ const { data, isLoading, refetch } = useLocalGhAuth();+ const [authenticating, setAuthenticating] = useState(false);+ const queryClient = useQueryClient();++ if (isLoading || !data) return null;++ const ready = data.ghInstalled && data.authenticated && data.canReadPackages;++ const problem = !data.ghInstalled+ ? 'GitHub CLI not installed'+ : !data.authenticated+ ? 'Not authenticated'+ : !data.canReadPackages+ ? 'Missing read:packages — re-run Authenticate'+ : null;++ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <span className="text-sm text-foreground">GitHub</span>+ {ready ? (+ <span className="flex items-center gap-1 text-xs text-green-500">+ <Check className="h-3.5 w-3.5" />+ {data.account ? `Authenticated as ${data.account}` : 'Authenticated'}+ </span>+ ) : (+ <span className="text-destructive flex items-center gap-1 text-xs">+ <AlertTriangle className="h-3.5 w-3.5" />+ {problem}+ </span>+ )}+ </div>+ {/* Also offered when the login is fine but lacks the scope — the fix is+ the same flow, and `gh auth refresh` adds it without a fresh login. */}+ {!ready && data.ghInstalled && !authenticating && (+ <Button size="xs" onClick={() => setAuthenticating(true)}>+ Authenticate+ </Button>+ )}+ {isLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ </div>++ {!data.ghInstalled && (+ <p className="text-xs text-foreground-muted">+ The Switch plugin and its MCP runtime are published privately on GitHub. Install the+ GitHub CLI from <span className="font-mono">cli.github.com</span>, then authenticate here.+ </p>+ )}++ {/* Re-authenticating cannot fix this one, so it says something different. */}+ {data.envShadowed && (+ <p className="text-xs text-amber-500">+ A <span className="font-mono">GH_TOKEN</span> /{' '}+ <span className="font-mono">GITHUB_TOKEN</span> environment variable is overriding your gh+ login, and it is what sessions will use. Authenticating again will not change that — unset+ it in your shell, or give that token the <span className="font-mono">read:packages</span>{' '}+ scope.+ </p>+ )}++ {authenticating && (+ <LocalGhAuthPanel+ onDone={() => {+ setAuthenticating(false);+ void refetch();+ // The plugin may now install where it could not before.+ void queryClient.invalidateQueries({ queryKey: ['switchSetup'] });+ }}+ />+ )}+ </div>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsx b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsxindex c7975c45f..9098b3c01 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsx@@ -10,6 +10,7 @@ import {UpdateAvailableBadge,UpdatingBadge,} from './agent-status-badge';+import { LocalGhAuthRow, useLocalGhAuth } from './LocalGhAuthRow';/*** Surfaces the Switch connector plugin status for an agent type and exposes@@ -30,10 +31,15 @@ export function SwitchSetupCard({ agentId }: { agentId: string }) {isUninstalling,} = useSwitchSetup(agentId);+ const { data: ghAuth } = useLocalGhAuth();+// Hide until we know the agent supports Switch setup.if (isLoading || !status?.supported) return null;const busy = isInstalling || isUpdating || isUninstalling || isChecking;+ // Until the probe answers, do not disable Install — a slow check should not+ // look like a blocked one.+ const ghReady = !ghAuth || (ghAuth.ghInstalled && ghAuth.authenticated && ghAuth.canReadPackages);const badge = isInstalling ? (<InstallingBadge />@@ -58,6 +64,7 @@ export function SwitchSetupCard({ agentId }: { agentId: string }) {<Field><Label>Switch setup</Label><div className="space-y-2 rounded-lg border p-3">+ <LocalGhAuthRow /><div className="flex items-center justify-between gap-2"><div className="flex items-center gap-2"><span className="text-sm text-foreground">switch-connector</span>@@ -66,7 +73,7 @@ export function SwitchSetupCard({ agentId }: { agentId: string }) {</div><div className="flex items-center gap-1.5">{!status.installed ? (- <Button size="xs" disabled={busy} onClick={() => install()}>+ <Button size="xs" disabled={busy || !ghReady} onClick={() => install()}>{isInstalling ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 'Install'}</Button>) : (@@ -101,6 +108,12 @@ export function SwitchSetupCard({ agentId }: { agentId: string }) {Couldn't refresh the plugin marketplace — showing cached status. {status.refreshError}</p>)}+ {!status.installed && !ghReady && (+ <p className="text-xs text-foreground-muted">+ The plugin is published to a private GitHub repository. Authenticate above to install+ it.+ </p>+ )}<p className="text-xs text-foreground-muted">Connects this agent to a Switch instance. Credentials are managed when you add the agentto a Switch server.diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-tools-unavailable-listener.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-tools-unavailable-listener.tsxnew file mode 100644index 000000000..f863d0742--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-tools-unavailable-listener.tsx@@ -0,0 +1,32 @@+import { useEffect } from 'react';+import { useToast } from '@renderer/lib/hooks/use-toast';+import { events } from '@renderer/lib/ipc';+import { switchToolsUnavailableEvent } from '@shared/events/switchSetupEvents';++const TITLE = 'Session started without Switch tools';++/**+ * Report a session that came up without its Switch MCP tools.+ *+ * The session still starts — that is deliberate — but without this the only+ * evidence was a log line, so it looked like a healthy session that simply had+ * no Switch tools, and the cause was several layers below anything the user+ * could see.+ */+export function SwitchToolsUnavailableListener() {+ const { toast } = useToast();++ useEffect(+ () =>+ events.on(switchToolsUnavailableEvent, ({ reason, detail }) => {+ const fix =+ reason === 'env-shadowed'+ ? 'Unset it in your shell, or give that token the read:packages scope.'+ : 'Fix this under Settings → Agents → Switch setup.';+ toast({ title: TITLE, description: `${detail} ${fix}`, variant: 'destructive' });+ }),+ [toast]+ );++ return null;+}diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/dialog-backgrounding.test.ts b/dash/apps/switchdash-desktop/src/renderer/lib/pty/dialog-backgrounding.test.tsnew file mode 100644index 000000000..a2060c0c0--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/dialog-backgrounding.test.ts@@ -0,0 +1,48 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it } from 'vitest';+import { isBackgroundedByDialog } from './dialog-backgrounding';++afterEach(() => {+ document.body.innerHTML = '';+});++function mount(html: string): HTMLElement | null {+ document.body.innerHTML = html;+ return document.querySelector<HTMLElement>('#term');+}++describe('isBackgroundedByDialog', () => {+ it('does not background a terminal when no dialog is open', () => {+ expect(isBackgroundedByDialog(mount('<div id="term"></div>'))).toBe(false);+ });++ it('backgrounds a terminal that sits behind a dialog', () => {+ const term = mount('<div id="term"></div><div role="dialog"></div>');+ expect(isBackgroundedByDialog(term)).toBe(true);+ });++ // The regression: a terminal rendered by the dialog is what the user is+ // typing into. Refusing its keys left `gh auth` waiting on an Enter that+ // could never arrive.+ it('does not background a terminal rendered inside the dialog', () => {+ const term = mount('<div role="dialog"><div id="term"></div></div>');+ expect(isBackgroundedByDialog(term)).toBe(false);+ });++ it('does not background a deeply nested terminal inside the dialog', () => {+ const term = mount('<div role="dialog"><section><p><div id="term"></div></p></section></div>');+ expect(isBackgroundedByDialog(term)).toBe(false);+ });++ it('checks every open dialog, not just the first', () => {+ const term = mount('<div role="dialog"></div><div role="dialog"><div id="term"></div></div>');+ expect(isBackgroundedByDialog(term)).toBe(false);+ });++ // Without an element there is nothing to compare against; staying blocked+ // preserves the old behaviour rather than letting keys through on a guess.+ it('backgrounds an unmounted terminal while a dialog is open', () => {+ mount('<div role="dialog"></div>');+ expect(isBackgroundedByDialog(null)).toBe(true);+ });+});diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/dialog-backgrounding.ts b/dash/apps/switchdash-desktop/src/renderer/lib/pty/dialog-backgrounding.tsnew file mode 100644index 000000000..818f4c0de--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/dialog-backgrounding.ts@@ -0,0 +1,18 @@+/**+ * Whether an open dialog has put this terminal in the background.+ *+ * False when the terminal is inside the dialog. The guard exists so a terminal+ * behind a modal does not eat keystrokes aimed at it; a terminal the modal+ * itself renders is the opposite case, and treating the two alike left an+ * interactive prompt (`gh auth`, waiting on Enter) with no way to answer.+ *+ * With no element to place there is nothing to compare against, so it stays+ * blocked — the previous behaviour, rather than letting keys through on a+ * guess.+ */+export function isBackgroundedByDialog(container: HTMLElement | null): boolean {+ const dialogs = document.querySelectorAll('[role="dialog"]');+ if (dialogs.length === 0) return false;+ if (!container) return true;+ return ![...dialogs].some((dialog) => dialog.contains(container));+}diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.ts b/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.tsindex 50ba9134e..cc47a6a93 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/use-pty.ts@@ -9,6 +9,7 @@ import { ptyDataChannel, ptyExitChannel } from '@shared/core/pty/ptyEvents';import { TERMINAL_FONT_SIZE_DEFAULT } from '@shared/core/terminals/terminal-settings';import { appPasteChannel } from '@shared/events/appEvents';import { getDomTabNavigationDirection } from '@shared/shortcuts';+import { isBackgroundedByDialog } from './dialog-backgrounding';import { usePaneSizingContext } from './pane-sizing-context';import type { FrontendPty, SessionTheme } from './pty';import { measureDimensions } from './pty-dimensions';@@ -290,9 +291,12 @@ export function usePty();const focus = useCallback(() => {- if (document.activeElement?.closest('[role="dialog"]')) return;+ // Do not steal focus from an open dialog — unless this terminal is the+ // thing inside it, in which case it is what the user is looking at.+ const activeDialog = document.activeElement?.closest('[role="dialog"]');+ if (activeDialog && !activeDialog.contains(containerRef.current)) return;termRef.current?.focus();- }, []);+ }, [containerRef]);const copySelectionToClipboard = useCallback(() => {const selection =@@ -438,7 +442,11 @@ export function usePty(// ── Keyboard shortcuts ─────────────────────────────────────────────────terminal.attachCustomKeyEventHandler((event: KeyboardEvent) => {- if (document.querySelector('[role="dialog"]')) return false;+ // A terminal in the background must not swallow keys meant for an open+ // dialog. One rendered *inside* the dialog is a different case: it is+ // what the user is typing into, and refusing its keys leaves an+ // interactive prompt with no way to answer it.+ if (isBackgroundedByDialog(containerRef.current)) return false;if (dispatchTerminalTabNavigationHotkey(event)) {event.preventDefault();diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.tsindex 4e3ddf1dd..f26a7a262 100644--- a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts@@ -12,4 +12,4 @@ export const RELEASE_REPO_OWNER = 'sandbox-quantum';export const RELEASE_REPO_NAME = 'switch';// Keep in sync with COMPATIBLE_SWITCH_VERSION in ./app-identity.ts.-export const COMPATIBLE_SWITCH_VERSION = '0.8.1';+export const COMPATIBLE_SWITCH_VERSION = '0.11.0';diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.tsindex b075e4f5c..afd9c12a2 100644--- a/dash/apps/switchdash-desktop/src/shared/app-identity.ts+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.ts@@ -27,4 +27,4 @@ export const RELEASE_REPO_NAME = 'switch';// artifact. Bump it in lockstep with the bundled compose// (src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml)// so a switchdash release pins a known-good switch-core stack.-export const COMPATIBLE_SWITCH_VERSION = '0.8.1';+export const COMPATIBLE_SWITCH_VERSION = '0.11.0';diff --git a/dash/apps/switchdash-desktop/src/shared/core/npm-registry.ts b/dash/apps/switchdash-desktop/src/shared/core/npm-registry.tsindex cdb225d5c..3132ab659 100644--- a/dash/apps/switchdash-desktop/src/shared/core/npm-registry.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/npm-registry.ts@@ -38,21 +38,89 @@ export const NPMRC_CONTENTS = [/** How to fix a token that authenticates but cannot read packages. */export const READ_PACKAGES_FIX = 'gh auth refresh -h github.com -s read:packages';+export const GH_HOST = 'github.com';++/** The scope the registry requires, which `gh auth login` does not request. */+export const READ_PACKAGES_SCOPE = 'read:packages';++/**+ * Ask `gh` which identity it will actually use, in machine-readable form.+ *+ * `--active` narrows the answer to the account that will be used, and `--json`+ * makes the scopes a field rather than a line of prose. Both matter: the human+ * output lists every known account, so a scope search over it answers a+ * question nobody asked — whether *some* account has the scope — and a second+ * account that does have it will vouch for one that does not.+ */+export const GH_AUTH_STATUS_ARGS = ['auth', 'status', '--active', '--json', 'hosts'];++/** What `gh` will do with the credentials it currently has. */+export type GhAuthState =+ | { status: 'ok'; login: string; scopes: string[]; tokenSource: string }+ | { status: 'missing-scope'; login: string; scopes: string[]; tokenSource: string }+ | { status: 'invalid'; tokenSource: string; detail: string }+ | { status: 'unknown' };++type GhAuthHostEntry = {+ state?: string;+ active?: boolean;+ login?: string;+ tokenSource?: string;+ scopes?: string;+ error?: string;+};+/**- * Whether `gh auth status` output describes a token that cannot read packages.+ * Interpret `gh auth status --active --json hosts`.*- * `gh auth login` asks for `gist`, `read:org`, `repo` and `workflow` — not- * `read:packages`. A perfectly healthy default login therefore yields a token- * the registry refuses with a 403 about "expected scopes", several layers below- * anything that mentions `gh`.+ * `tokenSource` is carried through because it names the origin of the+ * credential — a path for the keyring, or the literal `GH_TOKEN` when an+ * environment variable is shadowing it. When a login appears not to have taken+ * effect, that distinction is the answer, and it is not recoverable later.*- * Returns false when no scope line is present: the output is human-readable and- * may change, and being wrong about it must never block a session from starting.+ * Unrecognised output yields `unknown` rather than a guess. This gates setup,+ * and being confidently wrong about someone's working install is worse than+ * admitting the check did not apply.*/-export function lacksReadPackages(ghAuthStatusOutput: string): boolean {- return (- ghAuthStatusOutput.includes('Token scopes:') && !ghAuthStatusOutput.includes('read:packages')- );+export function parseGhAuthStatus(stdout: string): GhAuthState {+ let entries: GhAuthHostEntry[];+ try {+ const parsed = JSON.parse(stdout) as { hosts?: Record<string, GhAuthHostEntry[]> };+ entries = parsed.hosts?.[GH_HOST] ?? [];+ } catch {+ return { status: 'unknown' };+ }++ const active = entries.find((entry) => entry.active) ?? entries[0];+ if (!active) return { status: 'unknown' };++ const tokenSource = active.tokenSource ?? 'unknown';+ if (active.state !== 'success') {+ return {+ status: 'invalid',+ tokenSource,+ detail: active.error ?? 'gh reported the active token is not usable',+ };+ }++ if (active.scopes === undefined) return { status: 'unknown' };+ const scopes = active.scopes+ .split(',')+ .map((scope) => scope.trim().replace(/^'|'$/g, ''))+ .filter(Boolean);++ return {+ status: scopes.includes(READ_PACKAGES_SCOPE) ? 'ok' : 'missing-scope',+ login: active.login ?? '',+ scopes,+ tokenSource,+ };+}++/** Whether a token is shadowing the keyring, which survives re-authentication. */+export function isEnvShadowedToken(state: GhAuthState): boolean {+ if (state.status === 'unknown') return false;+ return state.tokenSource === 'GH_TOKEN' || state.tokenSource === 'GITHUB_TOKEN';}/** The environment that points npm at a written npmrc. */diff --git a/dash/apps/switchdash-desktop/src/shared/events/switchSetupEvents.ts b/dash/apps/switchdash-desktop/src/shared/events/switchSetupEvents.tsnew file mode 100644index 000000000..491a16b4d--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/events/switchSetupEvents.ts@@ -0,0 +1,16 @@+import { defineEvent } from '@shared/lib/ipc/events';++/**+ * A session started without the Switch MCP tools it was supposed to have.+ *+ * Sessions deliberately start anyway when the runtime cannot be fetched — one+ * with no MCP server beats none at all — but until this event the only trace+ * was a line in a log file, so the session looked healthy and simply had no+ * Switch tools. The reason distinguishes the fixes: `not-authenticated` and+ * `missing-scope` are resolved by the setup flow, while `env-shadowed` is not+ * resolved by authenticating at all.+ */+export const switchToolsUnavailableEvent = defineEvent<{+ reason: 'not-authenticated' | 'missing-scope' | 'invalid-token' | 'env-shadowed';+ detail: string;+}>('switch-setup:tools-unavailable');diff --git a/dash/apps/switchdash-desktop/src/sidecar/npm-registry-auth.ts b/dash/apps/switchdash-desktop/src/sidecar/npm-registry-auth.tsindex ce4869735..1e6e37ec3 100644--- a/dash/apps/switchdash-desktop/src/sidecar/npm-registry-auth.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/npm-registry-auth.ts@@ -3,9 +3,11 @@ import { mkdir, writeFile } from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';import {- lacksReadPackages,+ GH_AUTH_STATUS_ARGS,+ isEnvShadowedToken,NPMRC_CONTENTS,npmRegistryEnv,+ parseGhAuthStatus,READ_PACKAGES_FIX,} from '@shared/core/npm-registry';import type { WatcherLogger } from './notification-watcher';@@ -43,7 +45,7 @@ async function ghToken(log: WatcherLogger): Promise<string | null> {}/**- * Warn when the token cannot read packages.+ * Warn when the credentials `gh` will use cannot fetch the runtime.** `gh auth login` asks for `gist`, `read:org`, `repo` and `workflow` — not* `read:packages`. So the default, perfectly healthy login produces a token@@ -51,22 +53,39 @@ async function ghToken(log: WatcherLogger): Promise<string | null> {* "expected scopes", several layers below anything that mentions `gh`.** Checked here so the cause is stated at spawn, where it is actionable, rather- * than inferred later from an npx failure. Only a warning: the scope list is- * parsed from human-readable output, and being wrong about it must not stop a- * session starting.+ * than inferred later from an npx failure. Only a warning: an unrecognised+ * answer must not stop a session starting.*/-async function warnIfCannotReadPackages(log: WatcherLogger): Promise<void> {+async function warnAboutGhAuth(log: WatcherLogger): Promise<void> {try {- // `gh auth status` prints scopes on stderr.- const { stdout, stderr } = await execFileAsync('gh', ['auth', 'status'], { timeout: 10_000 });- if (!lacksReadPackages(`${stdout}${stderr}`)) return;- log.warn('npmRegistryAuth: the GitHub token cannot read packages', {- event: 'npm_registry_auth_missing_scope',- fix: READ_PACKAGES_FIX,- detail:- 'gh auth login does not request read:packages, so the registry will refuse ' +- 'with 403 and the session will start without its MCP tools',- });+ const { stdout } = await execFileAsync('gh', GH_AUTH_STATUS_ARGS, { timeout: 10_000 });+ const state = parseGhAuthStatus(stdout);+ if (isEnvShadowedToken(state)) {+ log.warn('npmRegistryAuth: an environment token is shadowing the gh login', {+ event: 'npm_registry_auth_env_shadowed',+ tokenSource: state.status === 'unknown' ? 'unknown' : state.tokenSource,+ detail:+ 'gh prefers GH_TOKEN/GITHUB_TOKEN over the keyring, so authenticating on ' ++ 'this host will not change which token is used until that variable is unset',+ });+ }+ if (state.status === 'missing-scope') {+ log.warn('npmRegistryAuth: the GitHub token cannot read packages', {+ event: 'npm_registry_auth_missing_scope',+ account: state.login,+ scopes: state.scopes.join(', '),+ fix: READ_PACKAGES_FIX,+ detail:+ 'gh auth login does not request read:packages, so the registry will refuse ' ++ 'with 403 and the session will start without its MCP tools',+ });+ } else if (state.status === 'invalid') {+ log.warn('npmRegistryAuth: the active GitHub token is not usable', {+ event: 'npm_registry_auth_invalid_token',+ tokenSource: state.tokenSource,+ detail: state.detail,+ });+ }} catch {// Never fatal — this is a diagnostic, not a gate.}@@ -93,7 +112,7 @@ export async function npmRegistryAuthEnv(return {};}- await warnIfCannotReadPackages(log);+ await warnAboutGhAuth(log);const dir = path.join(repoDir, '.switchdash');const npmrc = path.join(dir, 'npmrc');