Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): recheck credential requirements before completing reauthorization

zqchrisa1f19b901f51
diff --cc apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
index 00a22232d5,0000000000..c930c58ba8
mode 100644,000000..100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
@@@ -1,125 -1,0 +1,147 @@@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
++import type { GhostSetupAssessment } from '../../../shared/ghost';
+import type { BotAuthorizationCard } from '../../../shared/botAuthorization';
+import type { initBotAuthorizationService } from '../botAuthorizationService';
+
+const state = vi.hoisted(() => ({
++ assessment: vi.fn<() => GhostSetupAssessment>(),
++ subscribe: vi.fn((_id: string, _listener: (event: { source: string; ref?: string }) => void) => () => {}),
+ save: vi.fn(),
+ profileStatus: 'active',
+ login: vi.fn(async () => ({ ok: true })),
+ continued: vi.fn(),
+ policy: JSON.stringify({ toolsets: ['art'] }) as string | undefined,
+ deps: null as unknown as Parameters<typeof initBotAuthorizationService>[0],
+ execute: vi.fn(async () => ({ ok: true })),
+}));
+vi.mock('electron', () => ({ shell: { openExternal: vi.fn() } }));
+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+vi.mock('../botAuthorizationService.js', () => ({
+ initBotAuthorizationService: (deps: typeof state.deps) => { state.deps = deps; },
+}));
+vi.mock('../../localDb/client/current.js', () => ({
+ getDbClient: () => ({ drizzle: { select: (fields: Record<string, unknown>) => {
+ const query = {
+ from: () => query, innerJoin: () => query, where: () => query, orderBy: () => query,
+ limit: async () => 'resolvedJson' in fields
+ ? (state.policy === undefined ? [] : [{ resolvedJson: state.policy }])
+ : [{ id: 'bot', workingDir: '/bot', status: state.profileStatus }],
+ };
+ return query;
+ } } }),
+}));
+vi.mock('../../localDb/ipc/messages.js', () => ({
+ createMessage: state.save, patchMessageAgentMeta: vi.fn(),
+ broadcastMessageAgentMetaUpdate: vi.fn(), updateMessageContent: vi.fn(),
+}));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({}), isDataOwnerBroadcastScopeCurrent: () => true,
+}));
+vi.mock('../../cindy-brain/index.js', () => ({
+ getGhostManager: () => ({ list: () => [] }),
- getGhostSetupAssessment: () => ({ state: 'ready', revision: 1, groups: [] }),
++ getGhostSetupAssessment: state.assessment,
+ executeGhostSetupAction: state.execute, executeGhostSetupInlineAction: state.execute,
+ isGhostAvailableForActiveSession: () => true,
+ acquireGhostMutationLeaseForMcp: () => () => {}, captureGhostMutationOwnerForMcp: () => ({}),
+}));
+vi.mock('../../cindy-brain/ghostVisibility.js', () => ({
+ classifyGhostVisibility: () => ({ ok: true, ghost: { manifest: { id: 'art', name: 'Art' } } }),
+}));
+vi.mock('../../cindy-brain/ghostWorkdirPrefs.js', () => ({ isGhostDisabledForWorkdir: () => false }));
+vi.mock('../../cindy-brain/ghostSetupChangeBus.js', () => ({
- getGhostSetupChangeBus: () => ({ subscribe: () => () => {}, currentRevision: () => 1 }),
++ getGhostSetupChangeBus: () => ({ subscribe: state.subscribe, currentRevision: () => 1 }),
+}));
- vi.mock('../../cindy-brain/ghostSetupCoordinator.js', () => ({ toReauthInteractionAssessment: () => null }));
+vi.mock('../../maker-host/grok-oauth-login.js', () => ({
+ getGrokAccessToken: vi.fn(), hasGrokOAuthLogin: () => false, runGrokOAuthLogin: state.login,
+ getGrokOAuthCredentialGeneration: () => 0, cancelGrokOAuthLogin: vi.fn(),
+}));
+import { initializeBotAuthorizationHost } from '../botAuthorizationHost';
+
+const target = { kind: 'plugin' as const, id: 'art' };
+describe('authorization Host frozen plugin policy', () => {
+ beforeEach(() => {
++ state.assessment.mockReturnValue({ state: 'ready', revision: 1, groups: [] });
++ state.subscribe.mockClear();
+ state.policy = JSON.stringify({ toolsets: ['art'] });
+ state.save.mockClear();
+ state.profileStatus = 'active';
+ state.login.mockClear();
+ state.continued.mockClear();
+ state.execute.mockClear();
+ initializeBotAuthorizationHost(async (_card, validate) => {
+ await validate();
+ state.continued();
+ });
+ });
+
++ it('keeps credential A pending after credential B completes until A reauth is resolved', async () => {
++ const ready: GhostSetupAssessment = { state: 'ready', revision: 1, groups: [] };
++ state.assessment.mockReturnValue({ ...ready, reauthSuggest: {
++ ghostId: 'art', secretKey: 'A', missingScopes: ['write'], missingScopeCount: 1,
++ requirement: { ref: 'oauth:A', kind: 'oauth', label: 'Account A', action: { id: 'connect:A', kind: 'oauth_connect' } },
++ } });
++ const adapter = await state.deps.adapter('session', { ...target, reauthorize: true });
++ adapter.subscribe(vi.fn());
++ const callback = state.subscribe.mock.calls[0][1];
++ callback({ source: 'oauth', ref: 'B' });
++ await expect(adapter.assess()).resolves.toMatchObject({ state: 'required', groups: [{ id: 'reauth:A' }] });
++ // Even an action success is insufficient while the scope suggestion remains.
++ await adapter.execute({ id: 'connect:A', kind: 'oauth_connect' }, undefined);
++ await expect(adapter.assess()).resolves.toMatchObject({ state: 'required', groups: [{ id: 'reauth:A' }] });
++ state.assessment.mockReturnValue(ready);
++ await expect(adapter.assess()).resolves.toMatchObject({ state: 'ready' });
++ });
++
+ it('persists the validated credential-page link for the Desktop card', async () => {
+ await state.deps.adapter('session', target);
+ const card: BotAuthorizationCard = { v: 1, sessionId: 'session', target, createdAt: 1,
+ snapshot: { kind: 'plugin_setup', requestId: 'r', revision: 1, ghost: { id: 'art', name: 'Art' },
+ steps: [{ id: 'step', groupId: 'group', groupMode: 'any_of', title: 'Key', description: '', phase: 'pending',
+ action: { id: 'inline', kind: 'inline_form', form: { fields: [{ id: 'value', type: 'secret', label: 'Key',
+ required: true, maxLength: 4096, externalLink: { url: 'https://example.com/keys' } }] } } }] } };
+ await state.deps.save(card);
+ expect(state.save.mock.calls[0][1].agentMeta.botAuthorization.snapshot.steps[0].action.form.fields[0].externalLink)
+ .toEqual({ url: 'https://example.com/keys' });
+ });
+
+ it.each(['paused', 'archived', 'deleting', 'error'])('rejects old plugin and Host cards when the Profile is %s', async (status) => {
+ const plugin = await state.deps.adapter('session', target);
+ const hostTarget = { kind: 'host' as const, id: 'grok' as const };
+ const host = await state.deps.adapter('session', hostTarget);
+ state.profileStatus = status; // canonical Session remains active
+ for (const [adapter, cardTarget] of [[plugin, target], [host, hostTarget]] as const) {
+ await expect(state.deps.adapter('session', cardTarget)).rejects.toThrow('teammate is unavailable');
+ await expect(adapter.assess()).rejects.toThrow('teammate is unavailable');
+ await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).rejects.toThrow('teammate is unavailable');
+ await expect(state.deps.resume({ sessionId: 'session', target: cardTarget } as BotAuthorizationCard)).rejects.toThrow('teammate is unavailable');
+ }
+ expect(state.execute).not.toHaveBeenCalled();
+ expect(state.login).not.toHaveBeenCalled();
+ expect(state.continued).not.toHaveBeenCalled();
+ });
+
+ it.each([undefined, '{', '{}', '{"toolsets":[]}'])('rejects restored cards without an applied grant: %s', async (policy) => {
+ state.policy = policy;
+ await expect(state.deps.adapter('session', target)).rejects.toThrow('disabled in teammate profile');
+ expect(state.execute).not.toHaveBeenCalled();
+ });
+
+ it('rechecks the durable policy before assessment, credential mutation and continuation', async () => {
+ const adapter = await state.deps.adapter('session', target);
+ await expect(adapter.assess()).resolves.toMatchObject({ state: 'ready' });
+ state.policy = JSON.stringify({ toolsets: [] });
+ await expect(adapter.assess()).rejects.toThrow('disabled in teammate profile');
+ await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).rejects.toThrow('disabled in teammate profile');
+ await expect(state.deps.resume({ sessionId: 'session', target } as BotAuthorizationCard)).rejects.toThrow('disabled in teammate profile');
+ expect(state.execute).not.toHaveBeenCalled();
+ });
+
+ it('permits configured plugin actions and does not apply plugin policy to Host login', async () => {
+ const adapter = await state.deps.adapter('session', target);
+ await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).resolves.toMatchObject({ ok: true });
+ expect(state.execute).toHaveBeenCalledTimes(1);
+ state.policy = undefined;
+ await expect(state.deps.adapter('session', { kind: 'host', id: 'grok' })).resolves.toMatchObject({ identity: { id: 'grok' } });
+ });
+});
diff --cc apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
index a7139fa927,0000000000..1dd66a1803
mode 100644,000000..100644
--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
@@@ -1,379 -1,0 +1,382 @@@
+import { shell } from 'electron';
+import { t } from '../i18n.js';
+import { and, eq, isNull, ne, or, gt, like, desc, inArray } from 'drizzle-orm';
+import { getDbClient } from '../localDb/client/current.js';
+import { botSessionLinks, botProfiles, botRuntimeSnapshots, sessions, messages } from '../localDb/schema.js';
+import {
+ createMessage,
+ patchMessageAgentMeta,
+ broadcastMessageAgentMetaUpdate,
+ updateMessageContent,
+} from '../localDb/ipc/messages.js';
+import {
+ captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
+} from '../device-link/broadcast-tap.js';
+import {
+ getGhostManager,
+ getGhostSetupAssessment,
+ executeGhostSetupAction,
+ executeGhostSetupInlineAction,
+ isGhostAvailableForActiveSession,
+ acquireGhostMutationLeaseForMcp,
+ captureGhostMutationOwnerForMcp,
+} from '../cindy-brain/index.js';
+import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus.js';
+import { classifyGhostVisibility } from '../cindy-brain/ghostVisibility.js';
+import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
+import {
+ getGrokAccessToken,
+ hasGrokOAuthLogin,
+ runGrokOAuthLogin,
+ getGrokOAuthCredentialGeneration,
+ cancelGrokOAuthLogin,
+} from '../maker-host/grok-oauth-login.js';
+import { toReauthInteractionAssessment } from '../cindy-brain/ghostSetupCoordinator.js';
+import { initBotAuthorizationService } from './botAuthorizationService.js';
+import { readBotAuthorizationCard } from '../../shared/botAuthorization.js';
+import type { BotAuthorizationCard } from '../../shared/botAuthorization.js';
+import { sanitizeGhostSetupSnapshotForDesktop } from '../cindy-brain/ghostSetupInteractionBridge.js';
+import { createLogger } from '../logger.js';
+const log = createLogger('bot-authorization');
+
+/** Uses the canonical DB link, never an agent-supplied bot identity. */
+export async function isBotAuthorizationSession(sessionId: string): Promise<boolean> {
+ const [row] = await getDbClient()
+ .drizzle.select({ id: botSessionLinks.botId, status: botProfiles.status })
+ .from(botSessionLinks)
+ .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
+ .innerJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
+ .where(
+ and(
+ eq(botSessionLinks.sessionId, sessionId),
+ eq(botSessionLinks.role, 'canonical'),
+ isNull(botSessionLinks.archivedAt),
+ ne(sessions.status, 'deleted'),
+ ne(sessions.status, 'archived'),
+ ),
+ )
+ .limit(1);
+ return row?.status === 'active';
+}
+
+/** Adapts existing Host credentials and plugin configuration into the same card lifecycle. */
+export function initializeBotAuthorizationHost(
+ resume: (card: BotAuthorizationCard, validate: () => Promise<void>) => Promise<void>,
+) {
+ const ownerScopes = new Map<string, ReturnType<typeof captureDataOwnerBroadcastScope>>();
+ const assertPluginPolicy = async (sessionId: string, pluginId: string) => {
+ // The applied snapshot survives Host restarts; never infer teammate grants
+ // from global plugin visibility or from the card's display metadata.
+ const [snapshot] = await getDbClient()
+ .drizzle
+ .select({ resolvedJson: botRuntimeSnapshots.resolvedJson })
+ .from(botRuntimeSnapshots)
+ .where(
+ and(
+ eq(botRuntimeSnapshots.sessionId, sessionId),
+ inArray(botRuntimeSnapshots.status, ['applied', 'degraded']),
+ ),
+ )
+ .orderBy(desc(botRuntimeSnapshots.preparedAt))
+ .limit(1);
+ let resolved: { toolsets?: unknown } | null = null;
+ try {
+ resolved = JSON.parse(snapshot?.resolvedJson ?? 'null');
+ } catch {
+ /* deny malformed policy */
+ }
+ if (!Array.isArray(resolved?.toolsets) || !resolved.toolsets.includes(pluginId))
+ throw new Error('Plugin is disabled in teammate profile');
+ };
+ const assertSession = async (sessionId: string) => {
+ const scope = ownerScopes.get(sessionId);
+ if (
+ !scope ||
+ !isDataOwnerBroadcastScopeCurrent(scope) ||
+ !(await isBotAuthorizationSession(sessionId)) ||
+ !isDataOwnerBroadcastScopeCurrent(scope)
+ )
+ throw new Error('Authorization owner or teammate is unavailable');
+ };
+ return initBotAuthorizationService({
+ async adapter(sessionId, target) {
+ const scope = captureDataOwnerBroadcastScope();
+ if (!scope) throw new Error('Authorization owner unavailable');
+ const known = ownerScopes.get(sessionId);
+ if (known && !isDataOwnerBroadcastScopeCurrent(known))
+ throw new Error('Authorization owner changed');
+ ownerScopes.set(sessionId, scope);
+ await assertSession(sessionId);
+ const bus = getGhostSetupChangeBus();
+ if (target.kind === 'host') {
+ if (target.id !== 'grok') throw new Error('Unsupported Host connection');
+ const credentialGeneration = getGrokOAuthCredentialGeneration();
+ return {
+ identity: { id: 'grok', name: 'Grok' },
+ async assess() {
+ await assertSession(sessionId);
+ let ready = false;
+ if (
+ hasGrokOAuthLogin() &&
+ (!target.reauthorize || credentialGeneration !== getGrokOAuthCredentialGeneration())
+ ) {
+ try {
+ await getGrokAccessToken();
+ ready = hasGrokOAuthLogin();
+ } catch {
+ /* offer login */
+ }
+ }
+ await assertSession(sessionId);
+ if (target.reauthorize && credentialGeneration === getGrokOAuthCredentialGeneration())
+ ready = false;
+ return {
+ state: ready ? ('ready' as const) : ('required' as const),
+ revision: bus.currentRevision('host:grok'),
+ groups: ready
+ ? []
+ : [
+ {
+ id: 'grok-account',
+ mode: 'any_of' as const,
+ items: [
+ {
+ ref: 'grok-account',
+ kind: 'oauth' as const,
+ label: 'Grok',
+ state: 'missing' as const,
+ actions: [{ id: 'connect-grok', kind: 'oauth_connect' as const }],
+ },
+ ],
+ },
+ ],
+ };
+ },
+ subscribe: (wake) => bus.subscribe('host:grok', wake),
+ async execute(_action, _sender, _value, onAuthorizationUrl) {
+ await assertSession(sessionId);
+ const result = await runGrokOAuthLogin({ onAuthorizationUrl });
+ await assertSession(sessionId);
+ if (result.ok) {
+ bus.emit('host:grok', { source: 'oauth' });
+ return { ok: true as const };
+ }
+ return {
+ ok: false as const,
+ errorCode:
+ result.reason === 'timeout' ? ('TIMEOUT' as const) : ('AUTH_FAILED' as const),
+ };
+ },
+ };
+ }
+ const [session] = await getDbClient()
+ .drizzle.select({ workingDir: sessions.workingDir })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ const validate = async () => {
+ await assertSession(sessionId);
+ await assertPluginPolicy(sessionId, target.id);
+ await assertSession(sessionId);
+ const result = classifyGhostVisibility(target.id, session?.workingDir ?? null, {
+ listGhosts: () => getGhostManager().list(),
+ isAvailableForActiveSession: isGhostAvailableForActiveSession,
+ isDisabledForWorkdir: isGhostDisabledForWorkdir,
+ });
+ if (!result.ok) throw new Error('Plugin is unavailable');
+ return result.ghost;
+ };
+ const ghost = await validate();
+ let reconnected = false;
+ return {
+ identity: {
+ id: target.id,
+ name: ghost.manifest.name,
+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
+ },
+ async assess() {
+ await validate();
+ const assessment = getGhostSetupAssessment(target.id);
- if (!target.reauthorize || reconnected) return assessment;
++ if (!target.reauthorize) return assessment;
+ const suggested = toReauthInteractionAssessment(assessment);
++ // A plugin-wide OAuth event (or successful action) cannot satisfy a
++ // credential whose authoritative scope/reauth requirement still exists.
+ if (suggested) return suggested;
++ if (reconnected) return assessment;
+ if (assessment.state !== 'ready') return assessment;
+ const groups = assessment.groups.flatMap((group) => {
+ const items = group.items
+ .filter(
+ (item) =>
+ item.kind === 'oauth' &&
+ item.actions.some((action) => action.kind === 'oauth_connect'),
+ )
+ .map((item) => ({ ...item, state: 'expired' as const }));
+ return items.length ? [{ ...group, items }] : [];
+ });
+ return groups.length ? { ...assessment, state: 'required' as const, groups } : assessment;
+ },
+ subscribe: (wake) =>
+ bus.subscribe(target.id, (event) => {
+ if (event.source === 'oauth') reconnected = true;
+ wake();
+ }),
+ async execute(action, sender, value, onAuthorizationUrl) {
+ await validate();
+ const release = acquireGhostMutationLeaseForMcp(captureGhostMutationOwnerForMcp());
+ try {
+ if (action.kind === 'inline_form') {
+ if (value === undefined) return { ok: false, errorCode: 'INLINE_UNAVAILABLE' };
+ return await executeGhostSetupInlineAction({
+ sessionId,
+ ghostId: target.id,
+ action,
+ value,
+ });
+ }
+ const result = await executeGhostSetupAction({
+ sessionId,
+ ghostId: target.id,
+ action,
+ responseTarget: sender,
+ onAuthorizationUrl,
+ });
+ if (result.ok && action.kind === 'oauth_connect') reconnected = true;
+ return result;
+ } finally {
+ release();
+ }
+ },
+ };
+ },
+ async save(card) {
+ await assertSession(card.sessionId);
+ const [row] = await getDbClient()
+ .drizzle.select({ clearedAt: sessions.clearedAt })
+ .from(sessions)
+ .where(eq(sessions.id, card.sessionId))
+ .limit(1);
+ if (!row || (row.clearedAt !== null && row.clearedAt >= card.createdAt))
+ throw new Error('Authorization card was cleared');
+ card = {
+ ...card,
+ snapshot: {
+ ...sanitizeGhostSetupSnapshotForDesktop(card.snapshot),
+ ...(card.snapshot.reopenActionId ? { reopenActionId: card.snapshot.reopenActionId } : {}),
+ },
+ };
+ const clientId = `bot-authorization:${card.snapshot.requestId}`;
+ const phase = card.snapshot.steps.find((s) => s.phase !== 'satisfied')?.phase ?? 'satisfied';
+ const fallback = `${card.snapshot.ghost.name} · ${t(`newChat.pluginSetup.phase.${phase}`)}${card.snapshot.terminal ? '' : ` · ${t('newChat.pluginSetup.completeOnDesktop')}`}`;
+ // Only the presentation is stored. Current assessment/actions are re-read on every click.
+ await createMessage(
+ card.sessionId,
+ {
+ clientId,
+ role: 'assistant',
+ content: fallback,
+ agentMeta: { botAuthorization: card },
+ createdAt: card.createdAt,
+ },
+ {
+ broadcastOwnerScope: ownerScopes.get(card.sessionId),
+ expectedClearBoundaryMs: row.clearedAt,
+ },
+ );
+ await assertSession(card.sessionId);
+ await updateMessageContent(card.sessionId, clientId, fallback);
+ await patchMessageAgentMeta(card.sessionId, clientId, { botAuthorization: card });
+ await broadcastMessageAgentMetaUpdate(
+ card.sessionId,
+ clientId,
+ ownerScopes.get(card.sessionId),
+ );
+ },
+ async load(requestId) {
+ const [row] = await getDbClient()
+ .drizzle.select({ sessionId: messages.sessionId, meta: messages.agentMeta })
+ .from(messages)
+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))
+ .where(
+ and(
+ eq(messages.clientId, `bot-authorization:${requestId}`),
+ isNull(messages.rewindAt),
+ or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),
+ ),
+ )
+ .limit(1);
+ if (!row) return null;
+ const card = readStoredAuthorization(row);
+ return card?.snapshot.requestId === requestId ? card : null;
+ },
+ async findPending(sessionId, target) {
+ await assertSession(sessionId);
+ const rows = await getDbClient()
+ .drizzle.select({ sessionId: messages.sessionId, meta: messages.agentMeta })
+ .from(messages)
+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ like(messages.clientId, 'bot-authorization:%'),
+ isNull(messages.rewindAt),
+ or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),
+ ),
+ )
+ .orderBy(desc(messages.createdAt));
+ await assertSession(sessionId);
+ for (const row of rows) {
+ const card = readStoredAuthorization(row);
+ if (
+ card &&
+ !card.snapshot.terminal &&
+ card.target.kind === target.kind &&
+ card.target.id === target.id
+ )
+ return card;
+ }
+ return null;
+ },
+ async resume(card) {
+ await resume(card, async () => {
+ await assertSession(card.sessionId);
+ if (card.target.kind === 'plugin')
+ await assertPluginPolicy(card.sessionId, card.target.id);
+ const [row] = await getDbClient()
+ .drizzle.select({ id: messages.id })
+ .from(messages)
+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))
+ .where(
+ and(
+ eq(messages.sessionId, card.sessionId),
+ eq(messages.clientId, `bot-authorization:${card.snapshot.requestId}`),
+ isNull(messages.rewindAt),
+ or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),
+ ),
+ )
+ .limit(1);
+ if (!row) throw new Error('Authorization card is no longer visible');
+ await assertSession(card.sessionId);
+ });
+ },
+ onDisposing: () => cancelGrokOAuthLogin(),
+ onDispose: () => ownerScopes.clear(),
+ openExternal: (url) => shell.openExternal(url),
+ warn: () => log.warn('Authorization card operation failed'),
+ });
+}
+
+function readStoredAuthorization(row: {
+ sessionId: string;
+ meta: unknown;
+}): BotAuthorizationCard | null {
+ let meta: unknown;
+ try {
+ meta = typeof row.meta === 'string' ? JSON.parse(row.meta) : row.meta;
+ } catch {
+ return null;
+ }
+ const card = readBotAuthorizationCard((meta as Record<string, unknown> | null)?.botAuthorization);
+ return card?.sessionId === row.sessionId ? card : null;
+}