Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持 Grok 设备码登录与 Agent 协助授权 (#4960)
Chris Zhang16dc47255dde
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex ba57201997..892010ffb5 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -820,6 +820,7 @@ import {logoutGrok,hasGrokOAuthLogin,} from './maker-host/grok-oauth-login.js';+import { setGrokDeviceLoginConnectedHandler } from './maker-host/grok-device-login-service.js';import { setXaiAuthInvalidatedHandler } from './maker-host/xai-auth-invalidation-host.js';import { clearXaiMediaModels } from './maker-host/model-discovery/xai-media.js';import {@@ -5171,50 +5172,71 @@ const registerIpcHandlers = () => {})();});+ const finishXaiLogin = async (owner: string): Promise<boolean> => {+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return false;+ void retainProviderPresentationAfterAuthChange('xai');+ resetProviderModelAutoRefreshCooldowns('xai');+ await clearXaiSubscriptionUsageSnapshot();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return false;+ clearXaiDiscoveredModels();+ await discardXaiModelsDiskCache();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return false;+ clearXaiMediaModels();+ clearXaiRateLimitSnapshot();+ await syncXaiSubscriptionUsageForAuthChange();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return false;+ broadcastXaiAuthStateChanged();+ void refreshXaiModelsFromHttp();+ void refreshProviderModelsManually('xai').catch((error) => {+ createLogger('xai-model-refresh').warn('xAI models refresh after login failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ });+ return true;+ };+ setGrokDeviceLoginConnectedHandler(async (owner) => {+ await finishXaiLogin(owner);+ });+// xAI(SuperGrok 订阅)OAuth —— 与 claude-oauth 同形态。登录成功后 bridge 的 xai provider 立即可用// (buildHeaders 每请求现取 token);连接态由 renderer refetch listProviders 时现读 hasGrokOAuthLogin。- ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGIN, async (event) => {+ ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGIN, async (event, method?: 'browser' | 'device') => {assertTrustedAppRendererEvent(event);+ if (method !== undefined && method !== 'browser' && method !== 'device')+ throwIpcError('INVALID_ARGUMENT', 'Invalid xAI login method');const owner = activeOwnerScopeKey();// reason 是 renderer 决定提示用的结构化数据,不抛 throwIpcError(规则 13 查询型例外)。// 登录成功即生效:订阅直连 handler 每请求经 buildHeaders 现取凭证,无需任何"就绪"步骤。- const result = await runGrokOAuthLogin();+ const result = await runGrokOAuthLogin({+ method,+ onDeviceCode:+ method === 'device'+ ? (code) => {+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return;+ try {+ if (!event.sender.isDestroyed())+ event.sender.send(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {+ providerId: 'xai',+ phase: 'device-code',+ ...code,+ });+ } catch {+ /* window closed while auth continues */+ }+ }+ : undefined,+ });if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())return { ok: false, reason: 'login_cancelled', authorized: false };- if (result.ok) {- void retainProviderPresentationAfterAuthChange('xai');- resetProviderModelAutoRefreshCooldowns('xai');- // 新凭证在 runGrokOAuthLogin 返回前已经落盘。先同步关掉旧周用量读取窗口,- // 再去做模型磁盘清理等 await,避免换号间隙里 IPC read 仍返回账号 A 的快照。- await clearXaiSubscriptionUsageSnapshot();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())- return { ok: false, reason: 'login_cancelled', authorized: false };- // 登录可直接覆盖旧 SuperGrok 账号:先清旧世代内存,再直接读新账号官方清单。- // 这里不能先恢复同一 Cindy owner 的磁盘 LKG,否则 A→B 重登会短暂展示 A 的成员。- clearXaiDiscoveredModels();- await discardXaiModelsDiskCache();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())- return { ok: false, reason: 'login_cancelled', authorized: false };- // 登录可直接覆盖旧账号凭证。先跨授权边界清掉旧账号发现快照,再补拉新账号;- // 旧在途请求由 discovery generation + owner scope 双重守卫作废。- clearXaiMediaModels();- // 登录成功后广播 provider 变更 —— 其它已打开的窗口(聊天/模型选择器等)跟随刷新- // xAI 连接态,不再等 remount/手动刷新(对齐 CLAUDE_OAUTH_LOGIN 的 broadcastClaudeAuthStateChanged)。- // 限流快照是账号级的:重登可能换账号,旧快照一并清掉(等新账号首个 xai/ 轮自然补上)。- clearXaiRateLimitSnapshot();- await syncXaiSubscriptionUsageForAuthChange();- if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending())- return { ok: false, reason: 'login_cancelled', authorized: false };- broadcastXaiAuthStateChanged();- void refreshXaiModelsFromHttp();- void refreshProviderModelsManually('xai').catch((error) => {- createLogger('xai-model-refresh').warn('xAI models refresh after login failed', {- error: error instanceof Error ? error.message : String(error),- });- });- return { ok: true, authorized: true };- }- return { ok: false, reason: result.reason ?? 'unknown', authorized: hasGrokOAuthLogin() };+ if (result.ok)+ return (await finishXaiLogin(owner))+ ? { ok: true, authorized: true }+ : { ok: false, reason: 'login_cancelled', authorized: false };+ return {+ ok: false,+ reason: result.reason ?? 'unknown',+ authorized: hasGrokOAuthLogin(),+ };});ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGOUT,diff --git a/apps/desktop/src/main/maker-host/__tests__/grokDeviceLogin.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokDeviceLogin.test.tsnew file mode 100644index 0000000000..c8e44ae0af--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/grokDeviceLogin.test.ts@@ -0,0 +1,139 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++const openExternal = vi.hoisted(() => vi.fn());+vi.mock('electron', () => ({+ shell: { openExternal },+ app: {+ getPath: () => '/tmp/cindy-grok-device-test',+ getAppPath: () => '/tmp/cindy-grok-device-test',+ isPackaged: false,+ },+ safeStorage: { isEncryptionAvailable: () => false },+}));+vi.mock('../outbound-fetch.js', () => ({+ outboundFetch: (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init),+}));+vi.mock('../nativeProviderAuthBinding.js', () => ({+ bindNativeProviderAuth: vi.fn(),+ isNativeProviderAuthBound: () => true,+ unbindNativeProviderAuth: vi.fn(),+}));++import {+ cancelGrokOAuthLogin,+ runGrokOAuthLogin,+ type GrokDeviceCode,+ type GrokTokenBlob,+} from '../grok-oauth-login.js';++function response(status: number, body: unknown): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ } as Response;+}++afterEach(() => {+ cancelGrokOAuthLogin();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ openExternal.mockClear();+});++describe('Grok device authorization', () => {+ it('shows only the public short code, waits through authorization_pending, and stores tokens locally', async () => {+ vi.useFakeTimers();+ const requests: Array<{ url: string; body: URLSearchParams }> = [];+ let polls = 0;+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (!init?.method) return response(200, {});+ const body = new URLSearchParams(String(init.body));+ requests.push({ url, body });+ if (url.endsWith('/device/code'))+ return response(200, {+ device_code: 'private-device-code',+ user_code: 'ABCD-1234',+ verification_uri: 'https://auth.x.ai/device',+ expires_in: 120,+ interval: 5,+ });+ polls += 1;+ return polls === 1+ ? response(400, { error: 'authorization_pending' })+ : response(200, {+ access_token: 'private-access',+ refresh_token: 'private-refresh',+ expires_in: 3600,+ });+ }),+ );+ let showCode!: (code: GrokDeviceCode) => void;+ const codeReady = new Promise<GrokDeviceCode>((resolve) => {+ showCode = resolve;+ });+ let persisted: GrokTokenBlob | undefined;+ const login = runGrokOAuthLogin({+ method: 'device',+ onDeviceCode: showCode,+ persist: (blob) => {+ persisted = blob;+ },+ });+ const code = await codeReady;+ expect(code).toMatchObject({+ userCode: 'ABCD-1234',+ verificationUrl: 'https://auth.x.ai/device',+ });+ expect(JSON.stringify(code)).not.toContain('private-device-code');+ expect(openExternal).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(10_000);+ expect(await login).toEqual({ ok: true });+ expect(persisted).toMatchObject({+ access_token: 'private-access',+ refresh_token: 'private-refresh',+ });+ expect(requests[0]?.body.get('client_id')).toBeTruthy();+ expect(requests[1]?.body.get('grant_type')).toBe(+ 'urn:ietf:params:oauth:grant-type:device_code',+ );+ expect(requests[1]?.body.get('device_code')).toBe('private-device-code');+ });++ it('cancels pending device login without saving a credential', async () => {+ vi.useFakeTimers();+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ if (!init?.method) return response(200, {});+ if (String(input).endsWith('/device/code'))+ return response(200, {+ device_code: 'private-device-code',+ user_code: 'ABCD-1234',+ verification_uri: 'https://auth.x.ai/device',+ expires_in: 120,+ });+ return response(400, { error: 'authorization_pending' });+ }),+ );+ let showCode!: () => void;+ const codeReady = new Promise<void>((resolve) => {+ showCode = resolve;+ });+ const persist = vi.fn();+ const cancellation = new AbortController();+ const login = runGrokOAuthLogin({+ method: 'device',+ cancellationSignal: cancellation.signal,+ onDeviceCode: showCode,+ persist,+ });+ await codeReady;+ cancellation.abort();+ expect(await login).toMatchObject({ ok: false, reason: 'login_cancelled' });+ expect(persist).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/grokDeviceLoginOwnerSwitch.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokDeviceLoginOwnerSwitch.test.tsnew file mode 100644index 0000000000..713aa428a4--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/grokDeviceLoginOwnerSwitch.test.ts@@ -0,0 +1,68 @@+import { expect, it, vi } from 'vitest';++const session = vi.hoisted(() => ({+ owner: 'owner-a',+ oauthSlotBusy: false,+ signals: [] as AbortSignal[],+}));++vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => session.owner,+ isAppSessionBoundaryPending: () => false,+}));++vi.mock('../grok-oauth-login.js', () => ({+ hasGrokOAuthLogin: () => false,+ isGrokOAuthLoginInProgress: () => session.oauthSlotBusy,+ runGrokOAuthLogin: vi.fn(+ (opts: { cancellationSignal: AbortSignal; onDeviceCode: (code: object) => void }) => {+ if (session.oauthSlotBusy) throw new Error('OAuth slot still occupied');+ session.oauthSlotBusy = true;+ session.signals.push(opts.cancellationSignal);+ opts.onDeviceCode({+ verificationUrl: 'https://auth.x.ai/device',+ userCode: ['AAAA-1111', 'BBBB-2222', 'CCCC-3333'][session.signals.length - 1],+ expiresAt: Date.now() + 60_000,+ });+ return new Promise<{ ok: false; reason: string }>((resolve) => {+ opts.cancellationSignal.addEventListener('abort', () => {+ queueMicrotask(() => {+ session.oauthSlotBusy = false;+ resolve({ ok: false, reason: 'login_cancelled' });+ });+ });+ });+ },+ ),+}));++import {+ cancelGrokDeviceLogin,+ grokDeviceLoginStatus,+ startGrokDeviceLogin,+} from '../grok-device-login-service.js';+import { runGrokOAuthLogin } from '../grok-oauth-login.js';++it('releases the OAuth slot after an owner switch or cancellation before a new device login', async () => {+ expect(await startGrokDeviceLogin()).toMatchObject({ userCode: 'AAAA-1111' });++ session.owner = 'owner-b';+ const [first, second] = await Promise.all([startGrokDeviceLogin(), startGrokDeviceLogin()]);++ expect(session.signals[0]?.aborted).toBe(true);+ expect(first).toMatchObject({ userCode: 'BBBB-2222' });+ expect(second).toEqual(first);+ expect(grokDeviceLoginStatus()).toEqual(first);+ expect(runGrokOAuthLogin).toHaveBeenCalledTimes(2);++ expect(cancelGrokDeviceLogin()).toEqual({ status: 'failed', reason: 'cancelled' });+ const [retry, concurrentRetry] = await Promise.all([+ startGrokDeviceLogin(),+ startGrokDeviceLogin(),+ ]);+ expect(retry).toMatchObject({ userCode: 'CCCC-3333' });+ expect(concurrentRetry).toEqual(retry);+ expect(runGrokOAuthLogin).toHaveBeenCalledTimes(3);++ cancelGrokDeviceLogin();+});diff --git a/apps/desktop/src/main/maker-host/grok-device-login-service.ts b/apps/desktop/src/main/maker-host/grok-device-login-service.tsnew file mode 100644index 0000000000..ea8ac0f97f--- /dev/null+++ b/apps/desktop/src/main/maker-host/grok-device-login-service.ts@@ -0,0 +1,126 @@+import type { GrokLoginState } from '@cindy/mcps';+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';+import {+ hasGrokOAuthLogin,+ isGrokOAuthLoginInProgress,+ runGrokOAuthLogin,+ type GrokDeviceCode,+} from './grok-oauth-login.js';++interface Flight {+ owner: string;+ abort: AbortController;+ state: GrokLoginState;+ codeReady: Promise<GrokLoginState>;+ settled: Promise<void>;+}++let flight: Flight | null = null;+let onConnected: ((owner: string) => Promise<void>) | null = null;++/** Registered by the Desktop bootstrap, which owns provider cache reconciliation. */+export function setGrokDeviceLoginConnectedHandler(+ handler: (owner: string) => Promise<void>,+): void {+ onConnected = handler;+}++function currentOwner(): string | null {+ return isAppSessionBoundaryPending() ? null : activeOwnerScopeKey();+}++/** A single Host-owned flight is shared by every agent and window for the current owner. */+export async function startGrokDeviceLogin(): Promise<GrokLoginState> {+ const owner = currentOwner();+ if (!owner) throw new Error('Owner unavailable');+ if (flight && (flight.owner !== owner || flight.state.status === 'failed')) {+ const previous = flight;+ previous.abort.abort();+ previous.state = { status: 'failed', reason: 'cancelled' };+ await previous.settled;+ if (flight === previous) flight = null;+ if (currentOwner() !== owner) throw new Error('Owner unavailable');+ }+ if (hasGrokOAuthLogin()) return { status: 'connected' };+ if (+ flight?.owner === owner &&+ (flight.state.status === 'pending' || flight.state.status === 'idle')+ )+ return flight.codeReady;+ if (isGrokOAuthLoginInProgress()) throw new Error('Another Grok login is active');++ let reportCode!: (state: GrokLoginState) => void;+ const codeReady = new Promise<GrokLoginState>((resolve) => {+ reportCode = resolve;+ });+ const next: Flight = {+ owner,+ abort: new AbortController(),+ state: { status: 'idle' },+ codeReady,+ settled: Promise.resolve(),+ };+ flight = next;+ next.settled = runGrokOAuthLogin({+ method: 'device',+ cancellationSignal: next.abort.signal,+ onDeviceCode: (code: GrokDeviceCode) => {+ if (flight !== next || currentOwner() !== owner) return;+ next.state = {+ status: 'pending',+ verificationUrl: code.verificationUrl,+ userCode: code.userCode,+ expiresAt: code.expiresAt,+ };+ reportCode(next.state);+ },+ }).then(+ async (result) => {+ if (flight !== next || currentOwner() !== owner) {+ reportCode({ status: 'failed', reason: 'cancelled' });+ return;+ }+ if (result.ok) {+ next.state = { status: 'connected' };+ try {+ await onConnected?.(owner);+ } catch {+ /* login is already persisted */+ }+ } else {+ next.state = {+ status: 'failed',+ reason:+ result.reason === 'timeout'+ ? 'expired'+ : result.reason === 'access_denied'+ ? 'denied'+ : result.reason === 'login_cancelled'+ ? 'cancelled'+ : 'error',+ };+ }+ reportCode(next.state);+ },+ () => {+ next.state = { status: 'failed', reason: 'error' };+ reportCode(next.state);+ },+ );+ return codeReady;+}++export function grokDeviceLoginStatus(): GrokLoginState {+ const owner = currentOwner();+ if (!owner) return { status: 'idle' };+ if (hasGrokOAuthLogin()) return { status: 'connected' };+ return flight?.owner === owner ? flight.state : { status: 'idle' };+}++export function cancelGrokDeviceLogin(): GrokLoginState {+ if (flight?.owner !== currentOwner() || !['idle', 'pending'].includes(flight.state.status))+ return grokDeviceLoginStatus();+ flight.abort.abort();+ flight.state = { status: 'failed', reason: 'cancelled' };+ return flight.state;+}diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.tsindex 3e73b9e5cc..d42a9c5c84 100644--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts@@ -50,6 +50,8 @@ const OIDC_DISCOVERY_URL = 'https://auth.x.ai/.well-known/openid-configuration';// discovery 失败时的兜底端点(已实测,与 discovery 返回一致)。const FALLBACK_AUTHORIZE_URL = 'https://auth.x.ai/oauth2/authorize';const FALLBACK_TOKEN_URL = 'https://auth.x.ai/oauth2/token';+const FALLBACK_DEVICE_URL = 'https://auth.x.ai/oauth2/device/code';+const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';const SCOPE = 'openid profile email offline_access grok-cli:access api:access';// xAI 注册的固定回调(不可改端口 / 主机)。const REDIRECT_PORT = 56121;@@ -101,15 +103,22 @@ function assertXaiHttps(url: string, label: string): string {async function resolveEndpoints(signal: AbortSignal,-): Promise<{ authorize: string; token: string }> {+): Promise<{ authorize: string; token: string; device: string }> {try {const res = await outboundFetch(OIDC_DISCOVERY_URL, { signal });if (res.ok) {- const j = (await res.json()) as { authorization_endpoint?: string; token_endpoint?: string };+ const j = (await res.json()) as {+ authorization_endpoint?: string;+ token_endpoint?: string;+ device_authorization_endpoint?: string;+ };if (j.authorization_endpoint && j.token_endpoint) {return {authorize: assertXaiHttps(j.authorization_endpoint, 'authorize'),token: assertXaiHttps(j.token_endpoint, 'token'),+ device: j.device_authorization_endpoint+ ? assertXaiHttps(j.device_authorization_endpoint, 'device')+ : FALLBACK_DEVICE_URL,};}}@@ -119,7 +128,122 @@ async function resolveEndpoints(if (signal.aborted) throw err instanceof Error ? err : new Error('login_cancelled');/* 其余错误落兜底端点 */}- return { authorize: FALLBACK_AUTHORIZE_URL, token: FALLBACK_TOKEN_URL };+ return {+ authorize: FALLBACK_AUTHORIZE_URL,+ token: FALLBACK_TOKEN_URL,+ device: FALLBACK_DEVICE_URL,+ };+}++export interface GrokDeviceCode {+ userCode: string;+ verificationUrl: string;+ expiresAt: number;+}++async function waitForDevicePoll(ms: number, signal: AbortSignal): Promise<void> {+ if (signal.aborted) throw new Error('login_cancelled');+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(done, ms);+ function done() {+ signal.removeEventListener('abort', cancelled);+ resolve();+ }+ function cancelled() {+ clearTimeout(timer);+ signal.removeEventListener('abort', cancelled);+ reject(new Error('login_cancelled'));+ }+ signal.addEventListener('abort', cancelled, { once: true });+ });+}++async function pollDeviceAuthorization(+ deviceEndpoint: string,+ tokenEndpoint: string,+ signal: AbortSignal,+ onDeviceCode?: (code: GrokDeviceCode) => void,+): Promise<TokenResponse> {+ const response = await outboundFetch(deviceEndpoint, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ client_id: XAI_CLIENT_ID,+ scope: SCOPE,+ referrer: 'xdt-maker',+ }).toString(),+ signal,+ });+ if (!response.ok) throw new Error(`Device authorization failed (${response.status})`);+ const payload = (await response.json()) as {+ device_code?: unknown;+ user_code?: unknown;+ verification_uri?: unknown;+ verification_uri_complete?: unknown;+ expires_in?: unknown;+ interval?: unknown;+ };+ if (+ typeof payload.device_code !== 'string' ||+ !payload.device_code ||+ typeof payload.user_code !== 'string' ||+ !payload.user_code ||+ typeof payload.verification_uri !== 'string'+ )+ throw new Error('Invalid device authorization response');+ const verificationUrl = assertXaiHttps(payload.verification_uri, 'verification');+ const completeUrl =+ typeof payload.verification_uri_complete === 'string'+ ? assertXaiHttps(payload.verification_uri_complete, 'verification')+ : verificationUrl;+ const serverExpiresIn = Number(payload.expires_in);+ const expiresIn =+ Number.isFinite(serverExpiresIn) && serverExpiresIn > 0+ ? Math.max(1, Math.min(serverExpiresIn, 30 * 60))+ : 5 * 60;+ const expiresAt = Date.now() + expiresIn * 1000;+ onDeviceCode?.({+ userCode: payload.user_code,+ verificationUrl: completeUrl,+ expiresAt,+ });+ const serverInterval = Number(payload.interval);+ let interval =+ Number.isFinite(serverInterval) && serverInterval > 0+ ? Math.max(5, Math.min(serverInterval, 30))+ : 5;+ while (Date.now() < expiresAt) {+ await waitForDevicePoll(Math.min(interval * 1000, Math.max(0, expiresAt - Date.now())), signal);+ if (Date.now() >= expiresAt) break;+ const tokenResponse = await outboundFetch(tokenEndpoint, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: DEVICE_GRANT,+ client_id: XAI_CLIENT_ID,+ device_code: payload.device_code,+ }).toString(),+ signal,+ });+ if (tokenResponse.ok) {+ const token = (await tokenResponse.json()) as TokenResponse;+ if (!token.access_token) throw new Error('token 响应缺 access_token');+ return token;+ }+ const body = (await tokenResponse.json().catch(() => ({}))) as {+ error?: unknown;+ };+ if (body.error === 'authorization_pending') continue;+ if (body.error === 'slow_down') {+ interval = Math.min(interval + 5, 30);+ continue;+ }+ if (body.error === 'expired_token') throw new Error('timeout');+ if (body.error === 'access_denied' || body.error === 'authorization_denied')+ throw new Error('access_denied');+ throw new Error(`Device token exchange failed (${tokenResponse.status})`);+ }+ throw new Error('timeout');}function buildAuthUrl(@@ -463,6 +587,11 @@ export function cancelGrokOAuthLogin(providerId?: string): void {_currentListener?.close();}+/** Whether any xAI login owns the one process-wide authorization slot. */+export function isGrokOAuthLoginInProgress(): boolean {+ return _currentAbort !== null;+}+let credentialSequence = 0;/** Refresh mutex, token cache and invalidation generation belong to one owner/account. */function createGrokAccount(providerId: string) {@@ -564,6 +693,9 @@ function createGrokAccount(providerId: string) {}async function runGrokOAuthLogin(opts?: {+ method?: 'browser' | 'device';+ cancellationSignal?: AbortSignal;+ onDeviceCode?: (code: GrokDeviceCode) => void;onProgress?: (msg: string) => void;onAuthorizationUrl?: (url: string) => void;assertCurrent?: () => void;@@ -577,76 +709,84 @@ function createGrokAccount(providerId: string) {const challenge = genChallenge(verifier);const state = genState();const nonce = genState();- const listener = new CallbackListener();+ const listener = opts?.method === 'device' ? null : new CallbackListener();const abort = new AbortController();+ const cancelFromCaller = () => abort.abort();+ if (opts?.cancellationSignal?.aborted) abort.abort();+ else opts?.cancellationSignal?.addEventListener('abort', cancelFromCaller, { once: true });_currentListener = listener;_currentAbort = abort;_currentLoginKey = `${scope}:${providerId}`;let timer: ReturnType<typeof setTimeout> | null = null;try {- const { authorize, token } = await resolveEndpoints(abort.signal);+ const { authorize, token, device } = await resolveEndpoints(abort.signal);// resolveEndpoints 的 fetch 可被 abort,但 signal 可能在 await 返回后才被标记(race);// 显式检查避免在已取消状态下继续开回调 server 或开浏览器。if (abort.signal.aborted || !currentScope() || opts?.isCurrent?.() === false)throw new Error('login_cancelled');- await listener.start();+ if (listener) await listener.start();// listener.start() 同理:start 完成前取消会在后续 code-wait promise 被捕获,// 但 addEventListener 对已 aborted signal 不会再 fire —— 在此处提前检查保证不开浏览器。if (abort.signal.aborted || !currentScope() || opts?.isCurrent?.() === false)throw new Error('login_cancelled');- const authUrl = buildAuthUrl(authorize, challenge, state, nonce);-- // 必须先注册 code 等待(挂上 server 的 request handler + 超时 + 取消),再开浏览器 ——- // 已授权的浏览器可能在 openExternal 返回前就完成重定向,晚注册会丢掉那次回调请求,- // 登录只能干等到超时。- const codePromise = new Promise<string>((resolve, reject) => {- if (abort.signal.aborted) {- reject(new Error('login_cancelled'));- return;- }- timer = setTimeout(() => reject(new Error('timeout')), LOGIN_TIMEOUT_MS);- abort.signal.addEventListener('abort', () => reject(new Error('login_cancelled')), {- once: true,+ let tok: TokenResponse;+ if (!listener) {+ tok = await pollDeviceAuthorization(device, token, abort.signal, opts?.onDeviceCode);+ } else {+ const authUrl = buildAuthUrl(authorize, challenge, state, nonce);++ // 必须先注册 code 等待(挂上 server 的 request handler + 超时 + 取消),再开浏览器 ——+ // 已授权的浏览器可能在 openExternal 返回前就完成重定向,晚注册会丢掉那次回调请求,+ // 登录只能干等到超时。+ const codePromise = new Promise<string>((resolve, reject) => {+ if (abort.signal.aborted) {+ reject(new Error('login_cancelled'));+ return;+ }+ timer = setTimeout(() => reject(new Error('timeout')), LOGIN_TIMEOUT_MS);+ abort.signal.addEventListener('abort', () => reject(new Error('login_cancelled')), {+ once: true,+ });+ listener.waitForCode(state).then(resolve, reject);+ });+ // 预挂 no-op catch:openExternal 抛错走外层 catch 后,codePromise 稍后的 reject(超时/取消)+ // 不能变成 unhandled rejection;下方 await 仍能拿到同一 rejection,不受影响。+ codePromise.catch(() => {+ /* handled at await site */});- listener.waitForCode(state).then(resolve, reject);- });- // 预挂 no-op catch:openExternal 抛错走外层 catch 后,codePromise 稍后的 reject(超时/取消)- // 不能变成 unhandled rejection;下方 await 仍能拿到同一 rejection,不受影响。- codePromise.catch(() => {- /* handled at await site */- });- opts?.onProgress?.('opening-browser');- opts?.onAuthorizationUrl?.(authUrl);- log.info('opening browser for xai oauth', { port: REDIRECT_PORT });- await shell.openExternal(authUrl);+ opts?.onProgress?.('opening-browser');+ opts?.onAuthorizationUrl?.(authUrl);+ log.info('opening browser for xai oauth', { port: REDIRECT_PORT });+ await shell.openExternal(authUrl);- const code = await codePromise;+ const code = await codePromise;- opts?.onProgress?.('exchanging');- // form-encoded + PKCE 二次校验(challenge/method 再发一次)。- const res = await outboundFetch(token, {- method: 'POST',- headers: { 'content-type': 'application/x-www-form-urlencoded' },- body: new URLSearchParams({- grant_type: 'authorization_code',- client_id: XAI_CLIENT_ID,- code,- redirect_uri: REDIRECT_URI,- code_verifier: verifier,- code_challenge: challenge,- code_challenge_method: 'S256',- }).toString(),- signal: abort.signal,- });- if (!res.ok) {- const body = await res.text().catch(() => '');- throw new Error(`Token exchange failed (${res.status}): ${body.slice(0, 200)}`);+ opts?.onProgress?.('exchanging');+ // form-encoded + PKCE 二次校验(challenge/method 再发一次)。+ const res = await outboundFetch(token, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'authorization_code',+ client_id: XAI_CLIENT_ID,+ code,+ redirect_uri: REDIRECT_URI,+ code_verifier: verifier,+ code_challenge: challenge,+ code_challenge_method: 'S256',+ }).toString(),+ signal: abort.signal,+ });+ if (!res.ok) {+ const body = await res.text().catch(() => '');+ throw new Error(`Token exchange failed (${res.status}): ${body.slice(0, 200)}`);+ }+ tok = (await res.json()) as TokenResponse;+ if (!tok.access_token) throw new Error('token 响应缺 access_token');+ verifyIdTokenNonce(tok.id_token, nonce);}- const tok = (await res.json()) as TokenResponse;- if (!tok.access_token) throw new Error('token 响应缺 access_token');- verifyIdTokenNonce(tok.id_token, nonce);// token exchange 的 fetch 带 signal,但 res.json() / nonce 校验期间到达的 abort// 不会中断已 resolve 的响应体 —— 落盘前最后检查,保证"已取消"的登录绝不写凭证。@@ -662,17 +802,21 @@ function createGrokAccount(providerId: string) {_blobCache = next;if (providerId === 'xai') bindNativeProviderAuth('xai');advanceGrokOAuthCredentialGeneration();- listener.succeed();+ listener?.succeed();log.info('xai oauth login success', { scope: tok.scope });return { ok: true };} catch (err) {const msg = err instanceof Error ? err.message : String(err);- listener.fail(msg);+ listener?.fail(msg);log.warn('xai oauth login failed', { error: msg });- return { ok: false, reason: abort.signal.aborted ? 'login_cancelled' : msg };+ return {+ ok: false,+ reason: abort.signal.aborted ? 'login_cancelled' : msg,+ };} finally {+ opts?.cancellationSignal?.removeEventListener('abort', cancelFromCaller);if (timer) clearTimeout(timer);- listener.close();+ listener?.close();if (_currentListener === listener) _currentListener = null;if (_currentAbort === abort) {_currentAbort = null;diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex c1e6111d4a..8e665868c4 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -951,6 +951,11 @@ export function getMaker(): Maker {&& session.getStatus() === 'active'&& !session.remoteHostId);},+ isCurrentGrokLoginCaller: (sessionId: string, sessionInstanceId: string) => {+ const session = _maker?.getSession(sessionId);+ return Boolean(session && session.instanceId === sessionInstanceId+ && session.getStatus() === 'active' && !isAppSessionBoundaryPending());+ },// 只读活跃 Session 的运行时真相。权限切换是 runtime-first、DB-second,// 因此插件过户自动放行不得回退 sessions.permission_mode;会话不再 active// 时同样 fail closed。闭包在 MCP tool-call 时执行,此时 _maker 已装配完成。diff --git a/apps/desktop/src/main/maker-host/subscription-account-auth.ts b/apps/desktop/src/main/maker-host/subscription-account-auth.tsindex 2e05d3db4e..142e7558ba 100644--- a/apps/desktop/src/main/maker-host/subscription-account-auth.ts+++ b/apps/desktop/src/main/maker-host/subscription-account-auth.ts@@ -148,6 +148,10 @@ export function resetSubscriptionAccountCaches(): void {export async function loginSubscriptionAccount(providerId: string,isCurrent: () => boolean,+ options?: {+ method?: 'browser' | 'device';+ onDeviceCode?: (code: { userCode: string; verificationUrl: string; expiresAt: number }) => void;+ },): Promise<{ok: boolean;reason?: string;@@ -156,6 +160,7 @@ export async function loginSubscriptionAccount(}> {const kind = subscriptionAccountKind(providerId);if (!kind) throw new Error('Unknown subscription account');+ if (kind !== 'xai' && options?.method === 'device') throw new Error('Device login is only available for Grok');const scope = activeOwnerScopeKey();const key = `${scope}:${providerId}`;if (logins.has(key)) return { ok: false, reason: 'login_in_progress' };@@ -210,7 +215,12 @@ export async function loginSubscriptionAccount(persist,backfill: async () => {},})- : await runGrokOAuthLogin({ isCurrent: current, persist }, providerId);+ : await runGrokOAuthLogin({+ isCurrent: current,+ persist,+ method: options?.method,+ onDeviceCode: options?.onDeviceCode,+ }, providerId);if (!current()) {restoreWrittenCredentials();return { ok: false, reason: 'login_cancelled' };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex 31aed4b9be..6339f7c52a 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -4053,6 +4053,41 @@ describe('provider:oauth mutation ordering', () => {await login;});+ it('routes Grok device codes only to the owning renderer', async () => {+ const harness = new IpcHarness();+ const send = vi.fn();+ let progress!: (code: { userCode: string; verificationUrl: string; expiresAt: number }) => void;+ let finish!: (result: { ok: boolean }) => void;+ let receivedMethod: string | undefined;+ const owner = { dataOwnerId: 'owner-a', generation: 1 };+ registerProviderHandlers(harness, makeDeps({+ currentOwnerSession: () => ({ ...owner }),+ assertTrustedSender: (event: any) => { event.sender.send = send; },+ oauthLogin: async (_id, _current, _onBrowserUrl, method, onDeviceCode) => {+ receivedMethod = method;+ progress = onDeviceCode!;+ return new Promise(resolve => { finish = resolve; });+ },+ }));+ await expect(harness.invokeFrom(101, MAKER_INVOKE.PROVIDER_OAUTH_LOGIN,+ 'grok-account', { method: 'device' })).rejects.toThrow(/INVALID_PARAMS/);+ const login = harness.invokeFrom(101, MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, 'grok-account', {+ ownerId: 'attempt-grok', method: 'device',+ });+ await vi.waitFor(() => expect(progress).toBeDefined());+ expect(receivedMethod).toBe('device');+ progress({ userCode: 'ABCD-1234', verificationUrl: 'https://auth.x.ai/device', expiresAt: 12345 });+ expect(send).toHaveBeenCalledExactlyOnceWith(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {+ providerId: 'grok-account', phase: 'device-code', userCode: 'ABCD-1234',+ verificationUrl: 'https://auth.x.ai/device', expiresAt: 12345,+ });+ owner.generation++;+ progress({ userCode: 'LATE-1234', verificationUrl: 'https://auth.x.ai/device', expiresAt: 12345 });+ expect(send).toHaveBeenCalledTimes(1);+ finish({ ok: false });+ await login;+ });+it('invalidates post-login work when the provider is edited before discovery finishes', async () => {mountDb();const harness = new IpcHarness();diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 463a9730fc..4048602653 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -133,10 +133,18 @@ function requireProviderOAuthOwnerId(value: unknown, required = false): string |return value;}-function requireProviderOAuthLoginOptions(value: unknown): { ownerId?: string } {+function requireProviderOAuthLoginOptions(value: unknown): {+ ownerId?: string;+ method?: 'browser' | 'device';+} {if (value === undefined) return {};const options = providerOAuthOptions(value);- return { ownerId: requireProviderOAuthOwnerId(options.ownerId) };+ if (options.method !== undefined && options.method !== 'browser' && options.method !== 'device')+ throwIpcError('INVALID_PARAMS', 'method must be browser or device');+ return {+ ownerId: requireProviderOAuthOwnerId(options.ownerId),+ method: options.method as 'browser' | 'device' | undefined,+ };}function requireProviderOAuthCancelOptions(value: unknown): {@@ -333,6 +341,8 @@ export interface ProviderHandlerDeps {providerId: string,isCurrent: () => boolean,onBrowserUrl?: (url: string | null) => void,+ method?: 'browser' | 'device',+ onDeviceCode?: (code: { userCode: string; verificationUrl: string; expiresAt: number }) => void,): Promise<{ok: boolean;reason?: string;@@ -2335,8 +2345,10 @@ export function registerProviderHandlers(if (deps.isOrganizationManagedProviderId(id)) {throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');}- const { ownerId } = requireProviderOAuthLoginOptions(rawOptions);+ const { ownerId, method } = requireProviderOAuthLoginOptions(rawOptions);const sender = providerOAuthRendererSender(event);+ if (method === 'device' && !ownerId)+ throwIpcError('INVALID_PARAMS', 'device login requires an initiating window');if (ownerId && !sender) {throwIpcError('INVALID_PARAMS', 'ownerId requires an Electron sender');}@@ -2372,6 +2384,14 @@ export function registerProviderHandlers(providerId: id, ownerId, phase: 'browser-url', url,});} catch { /* A closed renderer must not interrupt credential cleanup. */ }+ }, method, (code) => {+ if (!ownerId || !sender || !isOAuthMutationCurrent(id, generation) ||+ !providerMutationOwnerMatches(ownerAtIngress)) return;+ try {+ sender.send?.(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {+ providerId: id, phase: 'device-code', ...code,+ });+ } catch { /* The login still runs if its initiating window closes. */ }});if (isOAuthMutationCurrent(id, generation)) {if (result.ok) {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 4dbeb17509..cd84d57653 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -5769,9 +5769,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},// 通用 OAuth(目录 auth.oauth 描述符驱动):login 成功后 best-effort 拉动态模型发现// (additions-only merge 进 active-catalog) 并广播 PROVIDER_CHANGED 让 UI 刷新连接态。- oauthLogin: async (providerId, isCurrent, onBrowserUrl) => {+ oauthLogin: async (providerId, isCurrent, onBrowserUrl, method, onDeviceCode) => {if (subscriptionAccountKind(providerId)) {- const result = await loginSubscriptionAccount(providerId, isCurrent);+ const result = await loginSubscriptionAccount(providerId, isCurrent, {+ method,+ onDeviceCode,+ });if (result.ok && isCurrent()) {if (subscriptionAccountKind(providerId) === 'xai') clearXaiRateLimitSnapshot(providerId);try { await refreshSubscriptionAccountModels(providerId); } catch { /* Static catalog remains usable. */ }@@ -5786,6 +5789,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}return result;}+ if (method === 'device') throw new Error('Device login is only available for Grok');if (isCodexAccountProvider(providerId)) {const owner = getActiveAppSession();const current = () => isCurrent() && getActiveAppSession().generation === owner.generation;diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 8c4a9c84db..0c2c90e302 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -91,6 +91,7 @@ import { isCindyLearnSkillEnabled } from '../skillhub/activationPreferences.js';import { getLearnController } from '../learn-host/index.js';import { consumeLearnInvocationGrant } from '../learn-host/invocationGrant.js';import { createSkillhubAgentTools } from '../skillhub/agentTools.js';+import { startGrokDeviceLogin, grokDeviceLoginStatus, cancelGrokDeviceLogin } from '../maker-host/grok-device-login-service.js';export interface DesktopMcpProvidersDeps {botCapabilities: Pick<ReturnType<typeof createBotCapabilityService>, 'list' | 'select'>;@@ -117,6 +118,8 @@ export interface DesktopMcpProvidersDeps {sessionId: string,sessionInstanceId: string | undefined,) => boolean;+ /** Current live session, including sessions whose agent runs over SSH. */+ isCurrentGrokLoginCaller?: (sessionId: string, sessionInstanceId: string) => boolean;/** 把工具结果图片转成文字描述(视觉桥,最佳努力)。缺失 = 不处理。* 返回结构区分「有意跳过」(skipped:true, 视觉桥未开/模型不命中, 不告警)与* 「真正尝试但失败」(skipped:false + null, 计入 attemptedCount 供告警)。 */@@ -382,6 +385,26 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// (LLM 调工具时) registerMakerIpc 早已执行完毕, holder 已 ready。xdtHelper: {logger: createLogger('mcp/cindy_helper'),+ grokLogin: {+ start: async (context) => {+ if (!context.sessionId || !context.sessionInstanceId+ || !deps.isCurrentGrokLoginCaller?.(context.sessionId, context.sessionInstanceId))+ throw new Error('Stale Grok login caller');+ return startGrokDeviceLogin();+ },+ status: async (context) => {+ if (!context.sessionId || !context.sessionInstanceId+ || !deps.isCurrentGrokLoginCaller?.(context.sessionId, context.sessionInstanceId))+ throw new Error('Stale Grok login caller');+ return grokDeviceLoginStatus();+ },+ cancel: async (context) => {+ if (!context.sessionId || !context.sessionInstanceId+ || !deps.isCurrentGrokLoginCaller?.(context.sessionId, context.sessionInstanceId))+ throw new Error('Stale Grok login caller');+ return cancelGrokDeviceLogin();+ },+ },sessionTags: async (callerSessionId, request) => {const result = await executeTaskTags(request, callerSessionId);return ['update', 'delete'].includes(request.action) ? { ...result, sessions: [] } : result;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex cf9dc71701..89cec7a90f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6014,7 +6014,7 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 通用 OAuth 供应商(目录 auth.oauth 描述符驱动)登录 / 登出 / 取消。 */providerOAuthLogin: (providerId: string,- options?: { ownerId?: string },+ options?: { ownerId?: string; method?: 'browser' | 'device' },): Promise<{ ok: boolean; reason?: string }> =>ipcRenderer.invoke('maker:provider:oauth:login', providerId, options),providerOAuthLogout: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> =>@@ -7052,8 +7052,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:claude-oauth:cancel', loginKey),// xAI(SuperGrok 订阅)OAuth —— 与 claudeOAuth* 同形态。- xaiOAuthLogin: (): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>- ipcRenderer.invoke('maker:xai-oauth:login'),+ xaiOAuthLogin: (method?: 'browser' | 'device'): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>+ ipcRenderer.invoke('maker:xai-oauth:login', method),xaiOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<{ authorized: boolean }> =>ipcRenderer.invoke('maker:xai-oauth:logout', ownerScope),xaiOAuthCancel: (): Promise<{ authorized: boolean }> =>diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex 382817b184..3d3ac70f0a 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -384,6 +384,7 @@ export function AddProviderWizard({offersManagedOllamaInstall(window.electronAPI.platform),);const [loggingIn, setLoggingIn] = useState(false);+ const [xaiDeviceLogin, setXaiDeviceLogin] = useState(false);const genericOAuthProviderId =sel?.kind === 'oauth' && sel.provider.auth.oauth ? sel.provider.id : null;const genericDeviceFlow =@@ -396,7 +397,7 @@ export function AddProviderWizard({beginOwnedLogin: beginGenericOwnedLogin,cancelOwnedLogin: cancelGenericOwnedLogin,} = useProviderOAuthDeviceCode(genericOAuthProviderId, {- observeProgress: genericDeviceFlow || (sel?.kind === 'oauth' && sel.provider.id === 'openai'),+ observeProgress: genericDeviceFlow || (sel?.kind === 'oauth' && ['openai', 'xai'].includes(sel.provider.id)),browserLoginRef: accountLoginRef,});// Step 3 拉取态@@ -778,14 +779,15 @@ export function AddProviderWizard({// ── OAuth 授权(渠道登录后进入模型选择,原生订阅沿用已有流程)────────────────────const handleAuthorize = useCallback(- async (override?: ProviderView) => {- const selected = override ?? (sel?.kind === 'oauth' ? sel.provider : undefined);+ async (method: 'browser' | 'device' = 'browser') => {+ const selected = sel?.kind === 'oauth' ? sel.provider : undefined;if (!selected) return;const attempt = ++oauthAttemptRef.current;let id = selected.id;const preset = presets.find(p => p.id === id && providerPresetOAuth(p.id));clearGenericDeviceCode();setLoggingIn(true);+ setXaiDeviceLogin(selected.id === 'xai' && method === 'device');try {let ok = false;if (id === 'openai' || id === 'anthropic' || id === 'xai' || preset) {@@ -803,7 +805,10 @@ export function AddProviderWizard({}, {});created = true;if (accountLoginRef.current !== login) return;- const result = await window.electronAPI.maker.providerOAuthLogin(id, { ownerId: login.ownerId });+ const result = await window.electronAPI.maker.providerOAuthLogin(id, {+ ownerId: login.ownerId,+ ...(brand === 'xai' ? { method } : {}),+ });if (accountLoginRef.current !== login || result.reason === 'login_cancelled') return;// A late success belongs to a cancelled wizard until ownership is checked.// Keep ok false so finally also removes credentials committed before cancellation.@@ -870,7 +875,10 @@ export function AddProviderWizard({toast.error(t('settings.providers.wizard.authorizeFailed', { name: selected.name }));} finally {// A cancelled account login may settle after a retry or local login has started.- if (!accountLoginRef.current && !localLoginRef.current) setLoggingIn(false);+ if (oauthAttemptRef.current === attempt && !accountLoginRef.current && !localLoginRef.current) {+ setLoggingIn(false);+ setXaiDeviceLogin(false);+ }}},[sel, presets, clearGenericDeviceCode, beginGenericOwnedLogin, onDone, t],@@ -894,6 +902,7 @@ export function AddProviderWizard({else cancelGenericOwnedLogin();clearGenericDeviceCode();setLoggingIn(false);+ setXaiDeviceLogin(false);}, [sel, clearGenericDeviceCode, cancelGenericOwnedLogin]);/** 关闭向导:授权等待中先取消再关,不留挂起的 login runner。保存中不能关,避免删掉正在落盘的 OAuth 连接。 */@@ -1811,6 +1820,11 @@ export function AddProviderWizard({: 'settings.providers.button.authorize',)}</Button>+ {sel.provider.id === 'xai' && (+ <Button variant="secondary" size="lg" type="button" onClick={() => void handleAuthorize('device')}>+ {t('settings.connections.xai.deviceLogin')}+ </Button>+ )}</>)}{/* 替代路径:API 用户没有订阅,OAuth 对其是错误路径——切到该渠道的@@ -1834,7 +1848,7 @@ export function AddProviderWizard({</Button>)}</div>- {genericDeviceFlow && loggingIn && (+ {(genericDeviceFlow || xaiDeviceLogin) && loggingIn && (<OAuthDeviceCodeCard deviceCode={genericDeviceCode} />)}{loggingIn && browserUrl && <OAuthBrowserLink url={browserUrl} />}diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsxindex 6c19b92fe2..f55a655916 100644--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx@@ -1033,26 +1033,67 @@ function XaiHeader({const { confirm } = useConfirmDialog();const [busy, setBusy] = useState(false);const [loggingIn, setLoggingIn] = useState(false);+ const [deviceLogin, setDeviceLogin] = useState(false);+ const [deviceCode, setDeviceCode] = useState<{+ verificationUrl: string;+ userCode: string;+ expiresAt: number;+ } | null>(null);+ const loginAttempt = useRef(0);+ useEffect(+ () => () => {+ loginAttempt.current += 1;+ },+ [],+ );const connected = provider?.connected ?? false;- const handleLogin = useCallback(async () => {- setLoggingIn(true);- try {- const r = await window.electronAPI.maker.xaiOAuthLogin();- if (r.ok) {- toast.success(t('settings.connections.xai.toast.loggedIn'));- onChanged();- } else if (r.reason === 'login_cancelled') {- /* 用户取消,不弹错 */- } else {- toast.error(t('settings.connections.xai.toast.loginFailed'));+ const handleLogin = useCallback(+ async (method: 'browser' | 'device') => {+ const attempt = ++loginAttempt.current;+ setLoggingIn(true);+ setDeviceLogin(method === 'device');+ setDeviceCode(null);+ const unsubscribe =+ method === 'device'+ ? window.electronAPI.maker.onProviderOAuthProgress((progress) => {+ if (+ attempt === loginAttempt.current &&+ progress.phase === 'device-code' &&+ progress.providerId === 'xai'+ )+ setDeviceCode({+ verificationUrl: progress.verificationUrl,+ userCode: progress.userCode,+ expiresAt: progress.expiresAt,+ });+ })+ : undefined;+ try {+ const r = await window.electronAPI.maker.xaiOAuthLogin(method);+ if (attempt !== loginAttempt.current) return;+ if (r.ok) {+ toast.success(t('settings.connections.xai.toast.loggedIn'));+ onChanged();+ } else if (r.reason === 'login_cancelled') {+ /* 用户取消,不弹错 */+ } else {+ toast.error(t('settings.connections.xai.toast.loginFailed'));+ }+ } catch {+ if (attempt === loginAttempt.current)+ toast.error(t('settings.connections.xai.toast.loginFailed'));+ } finally {+ unsubscribe?.();+ if (attempt === loginAttempt.current) {+ setLoggingIn(false);+ setDeviceLogin(false);+ setDeviceCode(null);+ }}- } catch {- toast.error(t('settings.connections.xai.toast.loginFailed'));- } finally {- setLoggingIn(false);- }- }, [onChanged, t]);+ },+ [onChanged, t],+ );const handleLogout = useCallback(async () => {try {@@ -1093,10 +1134,13 @@ function XaiHeader({),onClick: () => {if (loggingIn) {+ loginAttempt.current += 1;void window.electronAPI.maker.xaiOAuthCancel();setLoggingIn(false);+ setDeviceLogin(false);+ setDeviceCode(null);} else {- void handleLogin();+ void handleLogin('browser');}},};@@ -1104,6 +1148,17 @@ function XaiHeader({return (<DetailHeaderchildren={children}+ detail={+ !connected && (!loggingIn || deviceLogin) ? (+ deviceLogin ? (+ <OAuthDeviceCodeCard deviceCode={deviceCode} />+ ) : (+ <Button variant="secondary" size="md" onClick={() => void handleLogin('device')}>+ {t('settings.connections.xai.deviceLogin')}+ </Button>+ )+ ) : undefined+ }icon={<ProviderLogoMark providerId="xai" size={18} />}title={provider?.name ?? t('settings.providers.xai.title')}subtitle={providerSubtitleForDisplay(provider, t('settings.providers.xai.modelLabel'), {@@ -1138,6 +1193,7 @@ function GenericOAuthHeader({const confirmProviderChange = useProviderChangeConfirmation();const [busy, setBusy] = useState(false);const [loggingIn, setLoggingIn] = useState(false);+ const [xaiDeviceLogin, setXaiDeviceLogin] = useState(false);const connected = provider.connected;const loginAttempt = useRef(0);useEffect(@@ -1147,19 +1203,22 @@ function GenericOAuthHeader({[],);const deviceFlow = provider.auth.oauth?.flow === 'device-code';+ const xaiDeviceFlow = provider.auth.native === 'xai';const { deviceCode, browserUrl, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } =useProviderOAuthDeviceCode(provider.id, {- observeProgress: deviceFlow || provider.auth.native === 'codex',+ observeProgress: deviceFlow || xaiDeviceFlow || provider.auth.native === 'codex',});- const handleLogin = useCallback(async () => {+ const handleLogin = useCallback(async (method: 'browser' | 'device' = 'browser') => {const attempt = ++loginAttempt.current;clearDeviceCode();setLoggingIn(true);+ setXaiDeviceLogin(method === 'device');const ownedLogin = beginOwnedLogin();try {const r = await window.electronAPI.maker.providerOAuthLogin(provider.id, {ownerId: ownedLogin.ownerId,+ ...(xaiDeviceFlow ? { method } : {}),});if (attempt !== loginAttempt.current) return;if (r.ok) {@@ -1179,9 +1238,12 @@ function GenericOAuthHeader({);} finally {ownedLogin.finish();- if (attempt === loginAttempt.current) setLoggingIn(false);+ if (attempt === loginAttempt.current) {+ setLoggingIn(false);+ setXaiDeviceLogin(false);+ }}- }, [beginOwnedLogin, clearDeviceCode, onChanged, provider.id, provider.name, t]);+ }, [beginOwnedLogin, clearDeviceCode, onChanged, provider.id, provider.name, t, xaiDeviceFlow]);const handleLogout = useCallback(async () => {try {@@ -1237,6 +1299,7 @@ function GenericOAuthHeader({cancelOwnedLogin();clearDeviceCode();setLoggingIn(false);+ setXaiDeviceLogin(false);} else {void handleLogin();}@@ -1244,10 +1307,14 @@ function GenericOAuthHeader({disabled: busy,};const detail =- loggingIn && deviceFlow ? (+ loggingIn && (deviceFlow || xaiDeviceLogin) ? (<OAuthDeviceCodeCard deviceCode={deviceCode} />) : loggingIn && browserUrl ? (<OAuthBrowserLink url={browserUrl} />+ ) : !connected && !loggingIn && xaiDeviceFlow ? (+ <Button variant="secondary" size="md" onClick={() => void handleLogin('device')}>+ {t('settings.connections.xai.deviceLogin')}+ </Button>) : undefined;return (diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 344e2cd37b..7d03766171 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1691,6 +1691,7 @@}},"xai": {+ "deviceLogin": "Sign in with a code","logoutConfirm": {"title": "Disconnect xAI (SuperGrok)?","description": "Cindy will no longer use this Grok subscription.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 710d702707..f71aef2e75 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1691,6 +1691,7 @@}},"xai": {+ "deviceLogin": "コードでログイン","logoutConfirm": {"title": "xAI(SuperGrok)を切断しますか?","description": "Cindy はこの Grok サブスクリプションを使用できなくなります。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 8f6948f7c0..b6912ef354 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1691,6 +1691,7 @@}},"xai": {+ "deviceLogin": "코드로 로그인","logoutConfirm": {"title": "xAI(SuperGrok) 연결을 해제할까요?","description": "Cindy에서 이 Grok 구독을 사용할 수 없게 됩니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 7fcc6c51a1..a939b30fb3 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1691,6 +1691,7 @@}},"xai": {+ "deviceLogin": "用设备码登录","logoutConfirm": {"title": "断开 xAI(SuperGrok)?","description": "断开后,Cindy 将无法使用这份 Grok 订阅。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex ab64083cf6..17cd9ad7bb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1691,6 +1691,7 @@}},"xai": {+ "deviceLogin": "使用裝置碼登入","logoutConfirm": {"title": "斷開 xAI(SuperGrok)?","description": "中斷後,Cindy 將無法使用這份 Grok 訂閱。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8b2cb15d4e..a39a58a4bb 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5411,7 +5411,7 @@ interface ElectronAPI {/** 通用 OAuth 供应商(目录 auth.oauth 描述符驱动)登录 / 登出 / 取消。 */providerOAuthLogin: (providerId: string,- options?: { ownerId?: string },+ options?: { ownerId?: string; method?: 'browser' | 'device' },) => Promise<{ ok: boolean; reason?: string }>;providerOAuthLogout: (providerId: string,@@ -6400,8 +6400,8 @@ interface ElectronAPI {}) => Promise<{ authorized: boolean }>;/** 取消对应登录尝试。 */claudeOAuthCancel: (loginKey?: string) => Promise<{ authorized: boolean }>;- /** 拉起浏览器 OAuth 登录 xAI(SuperGrok 订阅);成功写 safeStorage。reason 在失败时给出 */- xaiOAuthLogin: () => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;+ /** 启动 xAI 浏览器或设备码 OAuth 登录;成功写 safeStorage。 */+ xaiOAuthLogin: (method?: 'browser' | 'device') => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;/** 登出 xAI(清本机 safeStorage 的 xai 凭证) */xaiOAuthLogout: (ownerScope?: {dataOwnerId: string | null;diff --git a/docs/product-rules/provider-settings.md b/docs/product-rules/provider-settings.mdindex 3dfae442bb..22ce47548c 100644--- a/docs/product-rules/provider-settings.md+++ b/docs/product-rules/provider-settings.md@@ -109,6 +109,7 @@ OpenAI、Claude 和 Grok 都允许新增独立登录账号。每次新增生成- 复用系统登录:明确「使用本机 Codex 账号」或「使用本机 Claude Code 账号」。- API 入口统一「API key 接入」。保存成功表示「已配置」,不能声称已经验证。- 「授权」只用于浏览器权限确认、设备授权码和 OAuth 端点等确实涉及授权的步骤。+- Grok 内置连接及独立账号支持浏览器回调和设备码两种订阅登录;设备码由 Cindy 显示给用户,用户在 xAI 授权页输入,Cindy 在本机完成轮询和凭证保存。Agent 可为当前 Cindy 账号启动内置 Grok 的设备码授权并查询状态,不接收长期凭证。- 状态统一「已连接/未连接/连接中」;管理动作统一「重命名/编辑连接设置/停用/启用/断开/删除」。- 断开保留连接以便恢复;删除不删除历史,也不承诺自动把原任务改用其他供应商。- 本机 Claude 与 Codex 均只撤销 Cindy 的使用许可;重新使用本机账号直接读取现有登录,无需新开浏览器。diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex 4b29cf13ad..da7ca570ce 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -18,6 +18,49 @@ function parsePayload(result: unknown): Record<string, unknown> {}describe("cindy_helper MCP server", () => {+ it('lets a remote agent start only the scoped Grok device login and returns no credential', async () => {+ let current = true;+ const start = vi.fn(async () => ({+ status: 'pending' as const,+ verificationUrl: 'https://auth.x.ai/device',+ userCode: 'ABCD-1234',+ expiresAt: Date.now() + 120_000,+ }));+ const server = createXdtHelperMcpServer({+ resolveSurface: async () => 'default',+ grokLogin: { start, status: async () => ({ status: 'idle' }), cancel: async () => ({ status: 'idle' }) },+ }, {+ agentKind: 'codex', workingDir: '', remoteHostId: 'remote-host',+ getSessionContext: () => current ? {+ agentKind: 'codex', workingDir: '/remote', remoteHostId: 'remote-host',+ sessionId: 'remote-session', sessionInstanceId: 'instance-1',+ } : undefined,+ });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ const client = new Client({ name: 'grok-remote-auth-test', version: '0.0.0' });+ await Promise.all([server.connect(st), client.connect(ct)]);+ try {+ const overview = parsePayload(await client.callTool({ name: 'list_tools', arguments: {} }));+ expect(overview.categories).toEqual([{ name: 'auth', tool_count: 3 }]);+ const result = parsePayload(await client.callTool({+ name: 'call_tool', arguments: { name: 'start_grok_device_login', args: {} },+ }));+ expect(result).toMatchObject({ status: 'pending', userCode: 'ABCD-1234' });+ expect(JSON.stringify(result)).not.toContain('access_token');+ expect(start).toHaveBeenCalledWith(expect.objectContaining({+ sessionId: 'remote-session', sessionInstanceId: 'instance-1', remoteHostId: 'remote-host',+ }));+ current = false;+ const stale = parsePayload(await client.callTool({+ name: 'call_tool', arguments: { name: 'start_grok_device_login', args: {} },+ }));+ expect(stale).toMatchObject({ ok: false, errorCode: 'NO_SESSION_CONTEXT' });+ expect(start).toHaveBeenCalledTimes(1);+ } finally {+ await client.close();+ await server.close();+ }+ });it("creates a teammate through the scoped helper entry", async () => {const create = vi.fn(async () => ({ok: true as const,diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 1f6aa04be6..705830bbe4 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -8,6 +8,7 @@ import { registerSessionTagTools, type SessionTagsCallback } from './xdt-helper/* - server name = `cindy_helper`,essential(常开,不可被用户关闭)* - 所有工具走 `list_tools` / `call_tool` 两个入口,渐进式发现:* - 'cindy' : 只读自省 (get_capabilities / get_current_session_id)+ * - 'auth' : 由 Host 保存凭证的供应商授权* - 'history' : 只读查询本地数据库聊天历史与输入队列 (list_workdirs /* list_sessions / list_session_queue / get_chat_history /* search_chat_history)@@ -32,6 +33,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { ListToolsRequestSchema, type Tool } from '@modelcontextprotocol/sdk/types.js';import { z } from 'zod';import { registerBotRoutineTools, type BotRoutineCallbacks } from './xdt-helper/botRoutineTools.js';+import { registerGrokLoginTools, type GrokLoginCallbacks } from './xdt-helper/grok_login.js';import { jsonObjectArg } from './json-object-arg.js';import { XdtHelperToolRegistry } from './lizi_xdtHelperToolRegistry.js';@@ -120,7 +122,7 @@ const CALL_TOOL_INPUT = {// list_tools 入口类目: cindy(自省) / control(会话控制面) / history(聊天历史) / feedback(官方反馈提交) / handoff(session 间 handoff)。// 协同 team 工具已拆到独立 cindy_orca server(插件开关 gate)。-const CATEGORY_ENUM = ['cindy', 'control', 'history', 'feedback', 'handoff', 'skills', 'bots'] as const;+const CATEGORY_ENUM = ['cindy', 'auth', 'control', 'history', 'feedback', 'handoff', 'skills', 'bots'] as const;interface SessionTaskCallbacks {startSessionTask(params: {@@ -621,6 +623,7 @@ export type ControlDispatchOutcome =export interface XdtHelperMcpDeps {logger?: LiziMcpLogger;+ grokLogin?: GrokLoginCallbacks;/** Host-owned runtime classification used to keep Bot tasks on a narrow surface. */resolveSurface?: (input: {sessionId: string;@@ -719,17 +722,21 @@ export function createXdtHelperMcpServer(const sessionId = context.sessionId;const remoteBotOnly = !!context.remoteHostId && context.agentKind !== 'pi';const defaultCategories = new Set(CATEGORY_ENUM.filter((category) => category !== 'bots'));- if (!sessionId || !deps.resolveSurface) return remoteBotOnly ? new Set() : defaultCategories;+ if (!sessionId) return remoteBotOnly ? new Set() : defaultCategories;+ if (!deps.resolveSurface) return remoteBotOnly ? new Set(['auth']) : defaultCategories;const surface = await deps.resolveSurface({ sessionId }).catch(() => 'restricted' as const);// Bot-specific memory, Skills, messaging, delegation and durable notes all// live in this single category. Cindy-wide history/control/feedback/handoff// stay out of the Bot's discovery loop.- if (surface === 'bot') return new Set(['bots', 'cindy']);- return remoteBotOnly || surface === 'restricted' ? new Set() : defaultCategories;+ if (surface === 'bot') return new Set(['bots', 'cindy', 'auth']);+ if (surface === 'restricted') return new Set();+ return remoteBotOnly ? new Set(['auth']) : defaultCategories;};// 'cindy' 类: 自省 (无 host 依赖, 始终注册)。registerGetCapabilitiesTool(registry);+ if (deps.grokLogin)+ registerGrokLoginTools(registry, () => resolveLiziMcpSessionContext(sessionCtx), deps.grokLogin);registerGetCurrentSessionIdTool(registry, {getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),});diff --git a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.tsindex a0ff58f6d5..7d96b17587 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts@@ -18,6 +18,7 @@ import { z } from 'zod';/*** Category 分两类:* - 'cindy' : 只读自省 (get_capabilities / get_current_session_id)+ * - 'auth' : Host 托管的供应商授权流程;短码可见,长期凭证不返回。* - 'history' : 只读查询本地数据库里的历史聊天数据 (list_workdirs /* list_sessions / get_chat_history / search_chat_history),* 方便用户自己组织 memory / 知识库系统@@ -41,6 +42,7 @@ import { z } from 'zod';*/export type XdtHelperToolCategory =| 'cindy'+ | 'auth'| 'history'| 'control'| 'feedback'diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.tsindex c1ea3b8d30..305ba4bbec 100644--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts@@ -27,6 +27,16 @@ export interface CapabilityEntry {}export const CAPABILITIES: readonly CapabilityEntry[] = [+ {+ key: 'grok-login',+ title: 'Grok / SuperGrok 授权登录',+ oneLiner: 'Grok 有浏览器跳转和设备短码两种登录方式;agent 可发授权页与短码并查询完成状态。',+ detail: [+ '浏览器跳转登录在设置的 Grok 连接卡中可用。',+ '设备码登录适合远程协助:agent 通过 cindy_helper 的 auth 类 start_grok_device_login 取得 xAI 授权页和短码,发给用户;用户在授权页输入短码并确认,Cindy 在本机自动轮询并保存凭证。',+ 'agent 可用 get_grok_login_status 查询连接状态,用户要求停止时可用 cancel_grok_device_login。长期 access token 和 refresh token 不会出现在工具返回值或聊天里;不要要求用户粘贴长期凭证。',+ ].join(' '),+ },{key: 'about-cindy',title: `${BRAND_NAME} 自身信息(产品身份 / 开源仓库 / 源码位置)`,diff --git a/packages/lizi-mcps/src/xdt-helper/grok_login.ts b/packages/lizi-mcps/src/xdt-helper/grok_login.tsnew file mode 100644index 0000000000..d0b4aa8fe1--- /dev/null+++ b/packages/lizi-mcps/src/xdt-helper/grok_login.ts@@ -0,0 +1,60 @@+import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';+import type { LiziMcpSessionContext } from '../types.js';+import { errorPayload, okPayload } from './_payload.js';++export type GrokLoginState =+ | { status: 'connected' }+ | {+ status: 'pending';+ verificationUrl: string;+ userCode: string;+ expiresAt: number;+ }+ | { status: 'failed'; reason: 'expired' | 'denied' | 'cancelled' | 'error' }+ | { status: 'idle' };++export interface GrokLoginCallbacks {+ start(context: LiziMcpSessionContext): Promise<GrokLoginState>;+ status(context: LiziMcpSessionContext): Promise<GrokLoginState>;+ cancel(context: LiziMcpSessionContext): Promise<GrokLoginState>;+}++export function registerGrokLoginTools(+ registry: XdtHelperToolRegistry,+ getContext: () => LiziMcpSessionContext,+ callbacks: GrokLoginCallbacks,+): void {+ const invoke = (action: 'start' | 'status' | 'cancel') => async () => {+ const context = getContext();+ if (!context.sessionId || !context.sessionInstanceId)+ return errorPayload('NO_SESSION_CONTEXT', '当前调用没有可验证的 Cindy 任务身份。');+ try {+ return okPayload(await callbacks[action](context));+ } catch {+ return errorPayload('AUTH_FAILED', '无法完成 Grok 授权,请稍后重试。');+ }+ };+ registry.register({+ name: 'start_grok_device_login',+ category: 'auth',+ description:+ '用户要求连接 Grok / SuperGrok 时启动设备码登录。返回 xAI 授权页和短码;请把两者展示给用户,让用户在授权页输入短码。浏览器自动回调是设置页中的另一种登录方式。短码由 Cindy 发给用户,不要求用户把它贴回聊天,也不返回长期凭证。随后可用 get_grok_login_status 查询结果。',+ inputShape: {},+ handler: invoke('start'),+ });+ registry.register({+ name: 'get_grok_login_status',+ category: 'auth',+ description:+ '查询当前 Grok 设备码登录是否完成;只在已经启动设备码登录后调用。pending 时用户仍需在 xAI 授权页输入短码,connected 表示凭证已由 Cindy 安全保存。',+ inputShape: {},+ handler: invoke('status'),+ });+ registry.register({+ name: 'cancel_grok_device_login',+ category: 'auth',+ description: '用户要停止本次 Grok 设备码授权时取消等待;已连接的凭证不会因此登出。',+ inputShape: {},+ handler: invoke('cancel'),+ });+}diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.tsindex 46b40fb52a..a0122d72f0 100644--- a/packages/lizi-mcps/src/xdt-helper/index.ts+++ b/packages/lizi-mcps/src/xdt-helper/index.ts@@ -9,6 +9,7 @@*/export { registerGetCapabilitiesTool } from './get_capabilities.js';+export { registerGrokLoginTools, type GrokLoginCallbacks, type GrokLoginState } from './grok_login.js';export { registerSkillhubTools, type SkillhubAgentCallback, type SkillhubAgentRequest } from './skillhub.js';export {registerGetCurrentSessionIdTool,