Skip to content

Commit cfdea39

Browse files
committed
fix(dashboard): integrate PR #862 to retain pending GitHub device sign-in
2 parents 95081b1 + e052ecd commit cfdea39

5 files changed

Lines changed: 222 additions & 13 deletions

File tree

‎apps/dashboard/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"@types/node": "^22.13.0",
4848
"@types/react": "^19.1.0",
4949
"@types/react-dom": "^19.1.0",
50+
"happy-dom": "^20.11.2",
5051
"postcss": "^8.5.8",
5152
"tailwindcss": "^4.2.1",
5253
"typescript": "^5.9.3",

‎apps/dashboard/src/app/(dashboard)/settings/_components/GitHubConnection.tsx‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,14 @@ export function GitHubConnection() {
130130
return () => window.removeEventListener(GITHUB_SOURCES_CHANGED_EVENT, refreshForSourceChange);
131131
}, [loadStatus]);
132132

133+
// The provider finishes device/token sign-in asynchronously. This card owns
134+
// a separate status snapshot, so refresh it when the pending action finishes.
135+
const previousActionRef = useRef(cliAction);
136+
useEffect(() => {
137+
if (previousActionRef.current && !cliAction) void loadStatus(true);
138+
previousActionRef.current = cliAction;
139+
}, [cliAction, loadStatus]);
140+
133141
// Connect/install opens a separate window (OAuth popup or the GitHub App
134142
// install tab). The connect call returns as soon as that window opens, so
135143
// the immediate loadStatus below is stale. Arm this flag on click and
@@ -285,19 +293,19 @@ export function GitHubConnection() {
285293
iconBg="bg-foreground/5"
286294
iconColor="text-foreground"
287295
>
288-
{loading ? (
289-
<div className="flex items-center gap-2 text-sm text-muted-foreground py-2">
290-
<div className="size-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
291-
{t.settings.github.checkingConnection}
292-
</div>
293-
) : !anyConnected && cliAction ? (
296+
{cliAction ? (
294297
/* A login is in flight. It's the only actionable thing on the card, so it
295298
replaces the chooser entirely instead of appearing underneath it. */
296299
<DeviceFlowPanel
297300
cliAction={cliAction}
298301
onRefresh={() => void loadStatus(true)}
299302
isDesktop={isDesktop}
300303
/>
304+
) : loading ? (
305+
<div className="flex items-center gap-2 text-sm text-muted-foreground py-2">
306+
<div className="size-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
307+
{t.settings.github.checkingConnection}
308+
</div>
301309
) : anyConnected ? (
302310
<div className="space-y-4">
303311
{/* The identity that is actually authorizing clones, first. */}
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// @vitest-environment happy-dom
2+
3+
import { act } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
import { GitHubProvider, type GitHubConnectionState } from "@/context/GitHubContext";
7+
import { GitHubConnection } from "./GitHubConnection";
8+
9+
const api = vi.hoisted(() => ({
10+
connect: vi.fn(),
11+
pollConnect: vi.fn(),
12+
getUserHome: vi.fn(),
13+
getStatusDeduped: vi.fn(),
14+
invalidateStatus: vi.fn(),
15+
showToast: vi.fn(),
16+
}));
17+
18+
vi.mock("@/lib/api", () => ({
19+
githubApi: api,
20+
settingsApi: { get: async () => ({}) },
21+
getApiErrorMessage: (error: Error) => error.message,
22+
GITHUB_SOURCES_CHANGED_EVENT: "github-sources-changed",
23+
}));
24+
vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ showToast: api.showToast }) }));
25+
vi.mock("@/context/CloudContext", () => ({ useCloud: () => ({ connected: false }) }));
26+
vi.mock("@/context/ModalContext", () => ({ useModal: () => ({}) }));
27+
vi.mock("@/context/PlatformContext", () => ({
28+
usePlatform: () => ({ selfHosted: true, deployMode: "docker" }),
29+
}));
30+
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
31+
32+
const disconnected: GitHubConnectionState = {
33+
primary: null,
34+
sources: {
35+
openshipApp: { connected: false },
36+
ghCli: { available: false, problem: "rejected", method: "device" },
37+
},
38+
};
39+
const connected: GitHubConnectionState = {
40+
primary: "gh-cli",
41+
sources: {
42+
openshipApp: { connected: false },
43+
ghCli: { available: true, login: "new-account", method: "device" },
44+
},
45+
};
46+
const deviceResponse = {
47+
connected: false,
48+
flow: "device_code",
49+
userCode: "ABCD-1234",
50+
verificationUri: "https://github.com/login/device",
51+
expiresIn: 899,
52+
interval: 5,
53+
};
54+
55+
let container: HTMLDivElement;
56+
let root: Root;
57+
58+
beforeEach(() => {
59+
vi.useFakeTimers();
60+
vi.clearAllMocks();
61+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
62+
api.connect.mockResolvedValue(deviceResponse);
63+
api.pollConnect.mockResolvedValue({ status: "pending" });
64+
api.getStatusDeduped.mockResolvedValue({ state: disconnected });
65+
api.getUserHome.mockResolvedValue({ state: disconnected });
66+
container = document.createElement("div");
67+
document.body.append(container);
68+
root = createRoot(container);
69+
});
70+
71+
afterEach(async () => {
72+
await act(async () => root.unmount());
73+
container.remove();
74+
vi.useRealTimers();
75+
vi.unstubAllGlobals();
76+
});
77+
78+
async function render(initialState = disconnected) {
79+
await act(async () => {
80+
root.render(
81+
<GitHubProvider initialData={{ state: initialState }}>
82+
<GitHubConnection />
83+
</GitHubProvider>,
84+
);
85+
});
86+
}
87+
88+
async function click(label: string) {
89+
const button = [...container.querySelectorAll("button")].find((el) =>
90+
el.textContent?.includes(label),
91+
);
92+
expect(button, `button: ${label}`).toBeDefined();
93+
await act(async () => button!.click());
94+
}
95+
96+
function expectDeviceInstructions() {
97+
expect(container.textContent).toContain(deviceResponse.userCode);
98+
expect(container.querySelector('a[href="https://github.com/login/device"]')).not.toBeNull();
99+
}
100+
101+
describe("Settings GitHub device sign-in (#851)", () => {
102+
it("shows the returned code, copies it, and updates the card after polling completes", async () => {
103+
const copy = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue();
104+
await render();
105+
await click("Sign in with GitHub");
106+
expectDeviceInstructions();
107+
await click(deviceResponse.userCode);
108+
expect(copy).toHaveBeenCalledWith(deviceResponse.userCode);
109+
110+
api.pollConnect.mockResolvedValue({ status: "complete" });
111+
api.getStatusDeduped.mockResolvedValue({ state: connected });
112+
api.getUserHome.mockResolvedValue({ state: connected });
113+
await act(async () => vi.advanceTimersByTimeAsync(5000));
114+
115+
expect(container.textContent).not.toContain(deviceResponse.userCode);
116+
expect(container.textContent).toContain("@new-account");
117+
expect(container.textContent).not.toContain("Sign in with GitHub");
118+
api.pollConnect.mockClear();
119+
await act(async () => vi.advanceTimersByTimeAsync(15000));
120+
expect(api.pollConnect).not.toHaveBeenCalled();
121+
copy.mockRestore();
122+
});
123+
124+
it("keeps device instructions when switching from an already connected App", async () => {
125+
const appState: GitHubConnectionState = {
126+
...disconnected,
127+
primary: "openship-app",
128+
sources: { ...disconnected.sources, openshipApp: { connected: true, login: "app-user" } },
129+
};
130+
api.getStatusDeduped.mockResolvedValue({ state: appState });
131+
api.getUserHome.mockResolvedValue({ state: appState });
132+
await render(appState);
133+
await click("Change method");
134+
await click("Sign in with GitHub");
135+
expectDeviceInstructions();
136+
await act(async () => vi.advanceTimersByTimeAsync(5000));
137+
expectDeviceInstructions();
138+
});
139+
140+
it("does not let stale provider connectivity dismiss a new device grant", async () => {
141+
// The library provider can still have its initial verified identity while
142+
// the Settings card's fresh probe reports that credential as rejected.
143+
await render(connected);
144+
await click("Sign in with GitHub");
145+
expectDeviceInstructions();
146+
await act(async () => vi.advanceTimersByTimeAsync(5000));
147+
expectDeviceInstructions();
148+
});
149+
150+
it("keeps the code visible while the card refreshes its status", async () => {
151+
await render();
152+
let resolveStatus!: (value: { state: GitHubConnectionState }) => void;
153+
api.getStatusDeduped.mockImplementationOnce(
154+
() =>
155+
new Promise((resolve) => {
156+
resolveStatus = resolve;
157+
}),
158+
);
159+
await click("Sign in with GitHub");
160+
expectDeviceInstructions();
161+
await act(async () => resolveStatus({ state: disconnected }));
162+
expectDeviceInstructions();
163+
});
164+
165+
it("returns to sign-in and surfaces the error when the device grant expires", async () => {
166+
await render();
167+
await click("Sign in with GitHub");
168+
api.pollConnect.mockResolvedValue({ status: "error", message: "The device code expired" });
169+
await act(async () => vi.advanceTimersByTimeAsync(5000));
170+
expect(container.textContent).not.toContain(deviceResponse.userCode);
171+
expect(container.textContent).toContain("Sign in with GitHub");
172+
expect(api.showToast).toHaveBeenCalledWith("The device code expired", "error", "GitHub");
173+
});
174+
});

‎apps/dashboard/src/context/GitHubContext.tsx‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,6 @@ export function GitHubProvider({ children, initialData }: GitHubProviderProps) {
257257
if (res?.capabilities) setCapabilities(res.capabilities as GitHubCapabilities);
258258

259259
if (nextState.primary !== null) {
260-
setCliAction(null);
261260
setAccounts(res.accounts ?? []);
262261
const primaryLogin =
263262
nextState.sources.openshipApp.login ?? nextState.sources.ghCli.login ?? "";
@@ -494,12 +493,12 @@ export function GitHubProvider({ children, initialData }: GitHubProviderProps) {
494493
}, [cliAction, refresh, showToast]);
495494

496495
/* ── Auto-detect a completed login ──────────────────────────── */
497-
// Any pending CLI action (the device flow OR a `gh auth login` the operator ran
498-
// on the instance) clears the moment the connection lands, so the UI never gets
499-
// stuck showing a code/command after success.
496+
// Only a terminal login completes through a status probe. A device grant has
497+
// its own authoritative poll above; a previously connected App or stale CLI
498+
// identity must not dismiss the new code before the operator authorizes it.
500499
useEffect(() => {
501-
if (connected && cliAction) setCliAction(null);
502-
}, [connected, cliAction]);
500+
if (cliAction?.type === "terminal" && state.sources.ghCli.available) setCliAction(null);
501+
}, [state.sources.ghCli.available, cliAction]);
503502

504503
// Terminal (`gh auth login`) has no device code to poll — refresh the status
505504
// periodically so the UI flips to connected as soon as the operator finishes,

0 commit comments

Comments
 (0)