Skip to content

Commit 47d4dd1

Browse files
OpenBitFun Agentwsp1911
authored andcommitted
fix(web-ui): create a terminal session for GitHub PR authentication
The GitHub CLI authentication action opened a terminal through the IDE-control quick action, which carries no session identity. The panel could therefore neither create the login terminal in the workspace that owns it nor keep it when the canvas path belonged to another workspace. Create the terminal through the shared manual terminal session service, resolve the owner workspace root and connection once before any await, re-check that owner before the PTY is presented, and open the returned session through the shared shell target with that owner scope. A missing, changed, or device-switched owner now reports the existing retryable error instead of silently retargeting the terminal.
1 parent 1a9334c commit 47d4dd1

2 files changed

Lines changed: 361 additions & 8 deletions

File tree

‎src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.test.tsx‎

Lines changed: 283 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,52 @@ import { createRoot, type Root } from 'react-dom/client';
44
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
55
import type { ReviewPlatformPullRequest, ReviewPlatformPullRequestDetailPage, ReviewPlatformPullRequestReviewTarget, ReviewPlatformWorkspaceSnapshot, ReviewRepositoryLocator } from '@/infrastructure/api/service-api/ReviewPlatformAPI';
66
import type { Session } from '@/flow_chat/types/flow-chat';
7+
import type { SessionResponse } from '@/tools/terminal/types/session';
78
import { ReviewPlatformPanel } from './ReviewPlatformPanel';
89
import { activateSurface } from '@/infrastructure/peer-device/deviceSurface';
910
import type { PeerHostCapabilities } from '@/infrastructure/peer-device/PeerConnectionManager';
1011

1112
const mocks = vi.hoisted(() => ({
1213
snapshot: vi.fn(), context: vi.fn(), detail: vi.fn(), openExternal: vi.fn(), reviewTarget: vi.fn(),
13-
prepareReview: vi.fn(),
14+
prepareReview: vi.fn(), setClipboard: vi.fn(),
15+
notify: { success: vi.fn(), warning: vi.fn(), error: vi.fn() },
1416
state: { sessions: new Map<string, Session>(), activeSessionId: null as string | null },
1517
t: (key: string) => key,
1618
}));
19+
// The panel must create a real manual session in its owning workspace and open
20+
// that returned identity, so both shared services stay observable here.
21+
const terminal = vi.hoisted(() => ({ create: vi.fn(), open: vi.fn() }));
22+
type StoredWorkspace = { rootPath?: string; workspaceKind?: string; connectionId?: string; name?: string };
23+
const workspaces = vi.hoisted(() => ({
24+
opened: new Map<string, StoredWorkspace>(),
25+
recent: [] as StoredWorkspace[],
26+
}));
1727
const peer = vi.hoisted(() => ({ active: false, capabilities: null as Partial<PeerHostCapabilities> | null }));
1828
vi.mock('@/infrastructure/peer-device/peerDeviceContextState', () => ({
1929
usePeerDeviceModeOptional: () => peer.active
2030
? { peerMode: { active: true }, currentPeerCapabilities: peer.capabilities }
2131
: null,
2232
}));
23-
vi.mock('@/infrastructure/api', () => ({ reviewPlatformAPI: { getWorkspaceSnapshot: mocks.snapshot, getWorkspaceContext: mocks.context, getPullRequestDetailPage: mocks.detail, getPullRequestReviewTarget: mocks.reviewTarget }, systemAPI: { openExternal: mocks.openExternal } }));
33+
vi.mock('@/infrastructure/api', () => ({ reviewPlatformAPI: { getWorkspaceSnapshot: mocks.snapshot, getWorkspaceContext: mocks.context, getPullRequestDetailPage: mocks.detail, getPullRequestReviewTarget: mocks.reviewTarget }, systemAPI: { openExternal: mocks.openExternal, setClipboard: mocks.setClipboard } }));
2434
vi.mock('@/infrastructure/markdown', () => ({ MarkdownRenderer: () => null }));
25-
vi.mock('@/shared/notification-system', () => ({ notificationService: {} }));
35+
vi.mock('@/shared/notification-system', () => ({ notificationService: mocks.notify }));
2636
vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: mocks.t }), i18nService: { t: mocks.t, formatDate: () => '' } }));
2737
vi.mock('@/flow_chat/services/sessionActivation', () => ({ openMainSession: vi.fn() }));
2838
vi.mock('@/flow_chat/services/btwSessionPane', () => ({ openBtwSessionInAuxPane: vi.fn() }));
2939
vi.mock('@/flow_chat/services/ReviewService', () => ({ launchPreparedReviewSession: vi.fn(), prepareReviewLaunchFromPullRequest: mocks.prepareReview }));
3040
vi.mock('@/flow_chat/components/DeepReviewConsentDialog', () => ({ useDeepReviewConsent: () => ({ confirmDeepReviewLaunch: vi.fn(), deepReviewConsentDialog: null }) }));
3141
vi.mock('@/flow_chat/store/FlowChatStore', () => ({ flowChatStore: { getState: () => mocks.state, subscribe: () => () => {} } }));
3242
vi.mock('@/shared/stores/contextStore', () => ({ useContextStore: {} }));
43+
// Kept empty: the panel must create a real session instead of asking the IDE
44+
// control facade for a terminal that carries no session identity.
3345
vi.mock('@/shared/services/ide-control', () => ({ quickActions: {} }));
46+
vi.mock('@/shared/services/createManualTerminalSession', () => ({ createManualTerminalSession: terminal.create }));
47+
vi.mock('@/shared/services/openShellSessionTarget', () => ({ openShellSessionTarget: terminal.open }));
48+
vi.mock('@/infrastructure/services/business/workspaceManager', () => ({
49+
workspaceManager: {
50+
getState: () => ({ openedWorkspaces: workspaces.opened, recentWorkspaces: workspaces.recent }),
51+
},
52+
}));
3453

3554
function pull(number: number, state: 'open' | 'merged'): ReviewPlatformPullRequest {
3655
return { id: String(number), number, state, title: `PR ${number}`, author: 'author', sourceBranch: 'feature', targetBranch: 'main',
@@ -87,6 +106,33 @@ async function mount() {
87106
return path;
88107
}
89108

109+
/** A GitHub workspace whose CLI session is missing, so the panel gates on auth. */
110+
function githubAuthSnapshot(path: string): ReviewPlatformWorkspaceSnapshot {
111+
const result = snapshot(path);
112+
const remote = result.remotes[0];
113+
remote.platform = 'github';
114+
remote.url = 'https://github.com/example/repo.git';
115+
remote.host = 'github.com';
116+
remote.authState = 'not_connected';
117+
result.repository = { ...result.repository!, platform: 'github', host: 'github.com' };
118+
result.pullRequests = [];
119+
result.pagination = { page: 1, perPage: 10, total: 0, hasNext: false };
120+
result.authChallenge = { platform: 'github', host: 'github.com', remoteId: remote.id,
121+
projectPath: 'example/repo', state: 'missing', message: '', requiredScopes: [] };
122+
return result;
123+
}
124+
125+
function buttonByText(owner: ParentNode, text: string): HTMLButtonElement | undefined {
126+
return [...owner.querySelectorAll<HTMLButtonElement>('button')]
127+
.find(button => (button.textContent ?? '').trim() === text);
128+
}
129+
130+
/** `exiting` proves the dialog started to close; its content is retained until then. */
131+
function authDialogState(): string | null {
132+
return document.querySelector('[data-openbitfun-component="dialog"][data-openbitfun-part="surface"]')
133+
?.getAttribute('data-state') ?? null;
134+
}
135+
90136
function statisticText(owner: Element, id: string): string | null | undefined {
91137
const lineStat = /^(pr|detail)-(additions|deletions)$/.exec(id);
92138
if (lineStat) {
@@ -111,6 +157,14 @@ describe('Gitee panel state and asynchronous request ordering', () => {
111157
mocks.openExternal.mockReset().mockResolvedValue(undefined);
112158
mocks.reviewTarget.mockReset();
113159
mocks.prepareReview.mockReset();
160+
mocks.setClipboard.mockReset().mockResolvedValue(undefined);
161+
mocks.notify.success.mockReset();
162+
mocks.notify.warning.mockReset();
163+
mocks.notify.error.mockReset();
164+
terminal.create.mockReset();
165+
terminal.open.mockReset();
166+
workspaces.opened.clear();
167+
workspaces.recent.length = 0;
114168
mocks.state.sessions.clear();
115169
mocks.state.activeSessionId = null;
116170
});
@@ -453,4 +507,230 @@ describe('Gitee panel state and asynchronous request ordering', () => {
453507
]));
454508
expect(trigger.getAttribute('aria-expanded')).toBe('false');
455509
});
510+
511+
describe('GitHub CLI authentication terminal', () => {
512+
const owningPath = '/owning-workspace';
513+
const owningId = workspaceIdFor(owningPath);
514+
const activeSessionOwner = 'workspace:some-other-workspace';
515+
const shell: SessionResponse = { id: 'terminal-42', name: 'Shell 7', shellType: 'bash',
516+
cwd: owningPath, status: 'running', cols: 80, rows: 24, source: 'manual' };
517+
518+
const mountAuthPanel = async (cwdPath = owningPath) => {
519+
mocks.snapshot.mockImplementation(({ repositoryPath }: ReviewRepositoryLocator) => Promise.resolve(githubAuthSnapshot(repositoryPath)));
520+
await act(async () => { root.render(<ReviewPlatformPanel workspaceId={owningId} workspacePath={cwdPath} />); });
521+
const authenticate = buttonByText(host, 'Authenticate');
522+
expect(authenticate).toBeDefined();
523+
await act(async () => { authenticate!.click(); });
524+
};
525+
const clickOpenTerminal = async () => {
526+
const openTerminal = buttonByText(document, 'Open terminal');
527+
expect(openTerminal).toBeDefined();
528+
await act(async () => { openTerminal!.click(); });
529+
};
530+
531+
beforeEach(() => {
532+
terminal.create.mockResolvedValue(shell);
533+
// The owning workspace is a remote workspace, so only its stored record
534+
// can name the connection the created terminal belongs to.
535+
workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'remote', connectionId: 'ssh-owner' });
536+
// The chat session executes elsewhere; it must never select the target.
537+
mocks.state.sessions.set('chat', {
538+
sessionId: 'chat', sessionKind: 'normal', workspaceId: activeSessionOwner, dialogTurns: [],
539+
} as Session);
540+
mocks.state.activeSessionId = 'chat';
541+
});
542+
543+
it('copies the login command and opens the returned session in the owning workspace', async () => {
544+
await mountAuthPanel();
545+
expect(authDialogState()).not.toBeNull();
546+
await clickOpenTerminal();
547+
expect(mocks.setClipboard).toHaveBeenCalledExactlyOnceWith('gh auth login --hostname github.com');
548+
expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: owningId, workspacePath: owningPath });
549+
expect(terminal.open).toHaveBeenCalledExactlyOnceWith({
550+
sessionId: 'terminal-42', sessionName: 'Shell 7',
551+
scope: { surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath, remoteConnectionId: 'ssh-owner' },
552+
});
553+
expect(terminal.open.mock.invocationCallOrder[0]).toBeGreaterThan(terminal.create.mock.invocationCallOrder[0]);
554+
expect(mocks.notify.success).toHaveBeenCalledOnce();
555+
expect(authDialogState()).toBe('exiting');
556+
});
557+
558+
it('keeps a retryable error and reports no success when creation fails', async () => {
559+
await mountAuthPanel();
560+
terminal.create.mockRejectedValueOnce(new Error('Terminal workspace ID is unavailable'));
561+
await clickOpenTerminal();
562+
expect(mocks.setClipboard).toHaveBeenCalledOnce();
563+
expect(terminal.open).not.toHaveBeenCalled();
564+
expect(mocks.notify.success).not.toHaveBeenCalled();
565+
expect(authDialogState()).toBe('open');
566+
expect(document.body.textContent).toContain('common:reviewPlatform.messages.openAuthFailed');
567+
expect(buttonByText(document, 'Open terminal')).toBeDefined();
568+
569+
// The retained dialog lets the user retry; the second click copies the
570+
// command again and creates the session that succeeds.
571+
await clickOpenTerminal();
572+
expect(mocks.setClipboard).toHaveBeenCalledTimes(2);
573+
expect(terminal.create).toHaveBeenCalledTimes(2);
574+
expect(terminal.open).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sessionId: 'terminal-42' }));
575+
expect(mocks.notify.success).toHaveBeenCalledOnce();
576+
});
577+
578+
it('keeps the retryable error without copying or creating when a remote owner has no connection', async () => {
579+
workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'remote' });
580+
await mountAuthPanel();
581+
await clickOpenTerminal();
582+
// The owner is resolved before the clipboard write, so nothing happens.
583+
expect(mocks.setClipboard).not.toHaveBeenCalled();
584+
expect(terminal.create).not.toHaveBeenCalled();
585+
expect(terminal.open).not.toHaveBeenCalled();
586+
expect(mocks.notify.success).not.toHaveBeenCalled();
587+
expect(authDialogState()).toBe('open');
588+
expect(document.body.textContent).toContain('common:reviewPlatform.messages.openAuthFailed');
589+
});
590+
591+
it('starts at the owner root when the panel path belongs to another workspace', async () => {
592+
await mountAuthPanel('/canvas-fallback-workspace');
593+
await clickOpenTerminal();
594+
expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: owningId, workspacePath: owningPath });
595+
expect(terminal.open).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
596+
scope: { surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath, remoteConnectionId: 'ssh-owner' },
597+
}));
598+
expect(mocks.notify.success).toHaveBeenCalledOnce();
599+
});
600+
601+
it('keeps a local owner scope free of any connection and an inside cwd', async () => {
602+
workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'normal' });
603+
await mountAuthPanel(`${owningPath}/src`);
604+
await clickOpenTerminal();
605+
expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: owningId, workspacePath: `${owningPath}/src` });
606+
const { scope } = terminal.open.mock.calls[0][0] as { scope: Record<string, unknown> };
607+
expect(scope).toEqual({ surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath });
608+
expect(scope).not.toHaveProperty('remoteConnectionId');
609+
expect(mocks.notify.success).toHaveBeenCalledOnce();
610+
});
611+
612+
it('keeps the retryable error when the owner connection changes during the clipboard write', async () => {
613+
const clipboard = deferred<void>();
614+
mocks.setClipboard.mockReturnValueOnce(clipboard.promise);
615+
await mountAuthPanel();
616+
await clickOpenTerminal();
617+
// The panel is still current, so only the owner check can stop this; the
618+
// service would otherwise create the PTY on the new connection.
619+
workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'remote', connectionId: 'ssh-reconnected' });
620+
await act(async () => clipboard.resolve());
621+
expect(terminal.create).not.toHaveBeenCalled();
622+
expect(terminal.open).not.toHaveBeenCalled();
623+
expect(mocks.notify.success).not.toHaveBeenCalled();
624+
expect(authDialogState()).toBe('open');
625+
expect(document.body.textContent).toContain('common:reviewPlatform.messages.openAuthFailed');
626+
expect(buttonByText(document, 'Open terminal')).toBeDefined();
627+
});
628+
629+
it('keeps the retryable error when the owner disappears during the clipboard write', async () => {
630+
const clipboard = deferred<void>();
631+
mocks.setClipboard.mockReturnValueOnce(clipboard.promise);
632+
await mountAuthPanel();
633+
await clickOpenTerminal();
634+
workspaces.opened.delete(owningId);
635+
await act(async () => clipboard.resolve());
636+
expect(terminal.create).not.toHaveBeenCalled();
637+
expect(terminal.open).not.toHaveBeenCalled();
638+
expect(mocks.notify.success).not.toHaveBeenCalled();
639+
expect(authDialogState()).toBe('open');
640+
});
641+
642+
it('keeps the retryable error when the owner disappears during creation', async () => {
643+
const creation = deferred<SessionResponse>();
644+
terminal.create.mockReturnValueOnce(creation.promise);
645+
await mountAuthPanel();
646+
await clickOpenTerminal();
647+
workspaces.opened.delete(owningId);
648+
await act(async () => creation.resolve(shell));
649+
// The host already owns the PTY; this only refuses to present it.
650+
expect(terminal.open).not.toHaveBeenCalled();
651+
expect(mocks.notify.success).not.toHaveBeenCalled();
652+
expect(authDialogState()).toBe('open');
653+
expect(document.body.textContent).toContain('common:reviewPlatform.messages.openAuthFailed');
654+
});
655+
656+
it('keeps the retryable error when the owner connection changes during creation', async () => {
657+
const creation = deferred<SessionResponse>();
658+
terminal.create.mockReturnValueOnce(creation.promise);
659+
await mountAuthPanel();
660+
await clickOpenTerminal();
661+
workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'remote', connectionId: 'ssh-reconnected' });
662+
await act(async () => creation.resolve(shell));
663+
expect(terminal.open).not.toHaveBeenCalled();
664+
expect(mocks.notify.success).not.toHaveBeenCalled();
665+
expect(authDialogState()).toBe('open');
666+
});
667+
668+
it('still opens the created session when the owner record only changed metadata', async () => {
669+
const creation = deferred<SessionResponse>();
670+
terminal.create.mockReturnValueOnce(creation.promise);
671+
await mountAuthPanel();
672+
await clickOpenTerminal();
673+
workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'remote', connectionId: 'ssh-owner', name: 'Renamed' });
674+
await act(async () => creation.resolve(shell));
675+
expect(terminal.open).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sessionId: 'terminal-42' }));
676+
expect(mocks.notify.success).toHaveBeenCalledOnce();
677+
});
678+
679+
it('does not open or notify when the panel unmounts during creation', async () => {
680+
const creation = deferred<SessionResponse>();
681+
terminal.create.mockReturnValueOnce(creation.promise);
682+
await mountAuthPanel();
683+
await clickOpenTerminal();
684+
await act(async () => { root.unmount(); });
685+
root = createRoot(host);
686+
await act(async () => creation.resolve(shell));
687+
expect(terminal.open).not.toHaveBeenCalled();
688+
expect(mocks.notify.success).not.toHaveBeenCalled();
689+
});
690+
691+
it('does not create a terminal when the clipboard copy settles after a device switch', async () => {
692+
const clipboard = deferred<void>();
693+
mocks.setClipboard.mockReturnValueOnce(clipboard.promise);
694+
await mountAuthPanel();
695+
await clickOpenTerminal();
696+
await act(async () => { activateSurface('auth-clipboard-peer'); });
697+
await act(async () => clipboard.resolve());
698+
expect(terminal.create).not.toHaveBeenCalled();
699+
expect(terminal.open).not.toHaveBeenCalled();
700+
expect(mocks.notify.success).not.toHaveBeenCalled();
701+
});
702+
703+
it('leaves a pending creation to the host instead of opening it on the new device', async () => {
704+
const creation = deferred<SessionResponse>();
705+
terminal.create.mockReturnValueOnce(creation.promise);
706+
await mountAuthPanel();
707+
await clickOpenTerminal();
708+
expect(terminal.create).toHaveBeenCalledOnce();
709+
await act(async () => { activateSurface('auth-create-peer'); });
710+
await act(async () => creation.resolve(shell));
711+
expect(terminal.open).not.toHaveBeenCalled();
712+
expect(mocks.notify.success).not.toHaveBeenCalled();
713+
});
714+
715+
it('does not reuse an abandoned creation after returning to the same device', async () => {
716+
const abandoned = deferred<SessionResponse>();
717+
terminal.create.mockReturnValueOnce(abandoned.promise);
718+
await act(async () => { activateSurface('auth-return-peer'); });
719+
await mountAuthPanel();
720+
await clickOpenTerminal();
721+
await act(async () => { activateSurface('auth-return-other-peer'); });
722+
await act(async () => { activateSurface('auth-return-peer'); });
723+
const returned = buttonByText(host, 'Authenticate');
724+
expect(returned).toBeDefined();
725+
await act(async () => { returned!.click(); });
726+
await act(async () => abandoned.resolve({ ...shell, id: 'abandoned-42' }));
727+
expect(terminal.open).not.toHaveBeenCalled();
728+
expect(mocks.notify.success).not.toHaveBeenCalled();
729+
730+
await clickOpenTerminal();
731+
expect(terminal.create).toHaveBeenCalledTimes(2);
732+
expect(terminal.open).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sessionId: 'terminal-42' }));
733+
expect(mocks.notify.success).toHaveBeenCalledOnce();
734+
});
735+
});
456736
});

0 commit comments

Comments
 (0)