Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

GitHub sign-in card: ask again before saying connected, and release a turn parked on a dismissed card

milind-soni85b08241fb4e
diff --git a/server/host/github-sign-in-cards.test.ts b/server/host/github-sign-in-cards.test.ts
index fa7521e49c..1724dd6a85 100644
--- a/server/host/github-sign-in-cards.test.ts
+++ b/server/host/github-sign-in-cards.test.ts
@@ -26,6 +26,7 @@ function setup(options: { team?: boolean; status?: GithubSignInStatus; person?:
const asked: string[] = [];
const reported: string[] = [];
const resumed: string[] = [];
+ const released: string[] = [];
const store = {
messagesFor: () => messages,
appendMessage: vi.fn((_threadId: string, message: Omit<Message, "id" | "at">) => { const row = { ...message, id: `m${messages.length + 1}`, at: 1 } as Message; messages.push(row); return row; }),
@@ -39,8 +40,9 @@ function setup(options: { team?: boolean; status?: GithubSignInStatus; person?:
language: () => undefined,
threadVisible: () => true,
resume: (threadId, resumeKey) => { resumed.push(`${threadId} ${resumeKey}`); },
+ release: (threadId, messageId) => { released.push(`${threadId} ${messageId}`); },
});
- return { cards, messages, store, asked, reported, resumed, set: (next: GithubSignInStatus) => { status = next; } };
+ return { cards, messages, store, asked, reported, resumed, released, set: (next: GithubSignInStatus) => { status = next; } };
}
const chief = { bot: { id: "chief", name: "Chief" }, threadId: "t1", from: { botId: "chief", name: "Chief", color: "blue" } } as const;
@@ -108,7 +110,7 @@ describe("the Connect GitHub card in a chat", () => {
});
it("settles when GitHub is connected, for its own person only; refuses an app authorize; can be set aside", async () => {
- const { cards, messages, set, resumed } = setup({ team: true });
+ const { cards, messages, set, resumed, released } = setup({ team: true });
await cards.raise(chief, { operation: "push", repo: "acme/site" });
const at = (auth: RequestAuth) => ({ auth, threadId: "t1", message: messages[0]! });
expect((await cards.route("authorize", "POST", at(member("[email protected]")))).status).toBe(409);
@@ -125,6 +127,7 @@ describe("the Connect GitHub card in a chat", () => {
expect(resumed).toHaveLength(1);
expect((await cards.route("dismiss", "POST", at(member("[email protected]")))).status).toBe(200);
expect(messages[0]!.connector!.dismissed).toBe(true);
+ expect(released).toEqual(["t1 m1"]);
const solo = setup();
await solo.cards.raise(chief, { operation: "push", repo: "acme/site" });
diff --git a/server/host/github-sign-in-cards.ts b/server/host/github-sign-in-cards.ts
index 6e5a83df27..3043e60b4e 100644
--- a/server/host/github-sign-in-cards.ts
+++ b/server/host/github-sign-in-cards.ts
@@ -49,6 +49,8 @@ export interface GithubSignInCardDeps {
threadVisible(auth: RequestAuth, threadId: string): boolean;
/** GitHub got connected: a turn parked on this card, if any, carries on. */
resume(threadId: string, resumeKey: string): void;
+ /** The card was set aside: a turn parked on it stops waiting. */
+ release(threadId: string, messageId: string): void;
}
type GithubCard = Message & { connector: ConnectorCardData };
@@ -99,6 +101,7 @@ export function createGithubSignInCards(deps: GithubSignInCardDeps) {
if (!isGithubSignInCard(card) || !deps.threadVisible(at.auth, at.threadId)) return { status: 404, body: { error: "no such connection request" } };
if (action === "dismiss" && method === "POST") {
store.patchMessage(at.threadId, card.id, { connector: { ...card.connector, dismissed: true } });
+ deps.release(at.threadId, card.id);
return { status: 200, body: { dismissed: true } };
}
if (action === "authorize" && method === "POST") return { status: 409, body: { error: serverLine(deps.language(at.threadId), "server.github.card.connectInApps") } };
diff --git a/server/index.ts b/server/index.ts
index eb0d23e105..75b3d66e58 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12059,7 +12059,7 @@ const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DA
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));
-ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) })); const githubSignInCards = createGithubSignInCards({ store, signIn: githubSignIn, team: Boolean(CLOUD_TEAM), turnPerson: (threadId, generation) => teamConnections.turnPerson(threadId, generation), language: threadLanguage, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), resume: (threadId, resumeKey) => void maybeResumeConnectors(threadId, resumeKey) }); provideGithubSignInCards(githubSignInCards);
+ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) })); const githubSignInCards = createGithubSignInCards({ store, signIn: githubSignIn, team: Boolean(CLOUD_TEAM), turnPerson: (threadId, generation) => teamConnections.turnPerson(threadId, generation), language: threadLanguage, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), resume: (threadId, resumeKey) => void maybeResumeConnectors(threadId, resumeKey), release: (threadId, messageId) => releaseCardNode(threadId, messageId, "The connection request was dismissed") }); provideGithubSignInCards(githubSignInCards);
ROUTES.push(createRoomHoldRoutes({
group: (id) => store.group(id),
groupFor: personRooms.groupForAuth,
diff --git a/src/components/PluginsPanel.disconnect.test.ts b/src/components/PluginsPanel.disconnect.test.ts
index b87b421e55..e6afbfd53f 100644
--- a/src/components/PluginsPanel.disconnect.test.ts
+++ b/src/components/PluginsPanel.disconnect.test.ts
@@ -35,7 +35,7 @@ vi.mock("@/lib/connector-oauth", () => ({
vi.mock("@/lib/product-events", () => ({ connectorConnect: vi.fn() }));
vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));
vi.mock("./github/GithubAppCard", () => ({ GITHUB_CARD_SEARCH: "github git", GITHUB_CARD_CATEGORIES: ["Developer tools"], GithubAppCard: () => null }));
-vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => false }));
+vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => true }));
vi.mock("./XCard", () => ({ X_CARD_SEARCH: "x", XCard: () => null }));
vi.mock("./PostizCard", () => ({ PostizCard: () => null }));
vi.mock("./EmailCard", () => ({ EmailCard: () => null }));
diff --git a/src/components/PluginsPanel.grants.test.ts b/src/components/PluginsPanel.grants.test.ts
index cb5c8469f9..00a0ebd8a3 100644
--- a/src/components/PluginsPanel.grants.test.ts
+++ b/src/components/PluginsPanel.grants.test.ts
@@ -42,7 +42,7 @@ vi.mock("@/lib/connector-oauth", () => ({
vi.mock("@/lib/product-events", () => ({ connectorConnect: vi.fn() }));
vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));
vi.mock("./github/GithubAppCard", () => ({ GITHUB_CARD_SEARCH: "github git", GITHUB_CARD_CATEGORIES: ["Developer tools"], GithubAppCard: () => null }));
-vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => false }));
+vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => true }));
vi.mock("./XCard", () => ({ X_CARD_SEARCH: "x", XCard: () => null }));
vi.mock("./PostizCard", () => ({ PostizCard: () => null }));
vi.mock("./EmailCard", () => ({
diff --git a/src/components/PluginsPanel.listing.test.ts b/src/components/PluginsPanel.listing.test.ts
index 56181c98af..84eb223985 100644
--- a/src/components/PluginsPanel.listing.test.ts
+++ b/src/components/PluginsPanel.listing.test.ts
@@ -51,7 +51,7 @@ vi.mock("@/lib/connected-apps-cache", () => ({ readCachedInventory: () => null,
vi.mock("@/lib/product-events", () => ({ connectorConnect: vi.fn() }));
vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));
vi.mock("./github/GithubAppCard", () => ({ GITHUB_CARD_SEARCH: "github git", GITHUB_CARD_CATEGORIES: ["Developer tools"], GithubAppCard: () => null }));
-vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => false }));
+vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => true }));
vi.mock("./XCard", () => ({ X_CARD_SEARCH: "x", XCard: () => null }));
vi.mock("./PostizCard", () => ({ PostizCard: () => null }));
vi.mock("./EmailCard", () => ({ EmailCard: () => null }));
diff --git a/src/components/PluginsPanel.member.test.ts b/src/components/PluginsPanel.member.test.ts
index 00a4895ce2..be1dc4b3d0 100644
--- a/src/components/PluginsPanel.member.test.ts
+++ b/src/components/PluginsPanel.member.test.ts
@@ -10,7 +10,7 @@ vi.mock("@/state/store", () => ({
}));
vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));
vi.mock("./github/GithubAppCard", () => ({ GITHUB_CARD_SEARCH: "github git", GITHUB_CARD_CATEGORIES: ["Developer tools"], GithubAppCard: () => null }));
-vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => false }));
+vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => true }));
vi.mock("./XCard", () => ({ X_CARD_SEARCH: "x", XCard: () => null }));
const { PluginsPanel } = await import("./PluginsPanel");
diff --git a/src/components/PluginsPanel.navigation.test.ts b/src/components/PluginsPanel.navigation.test.ts
index 7c71b9ed86..434f990cb8 100644
--- a/src/components/PluginsPanel.navigation.test.ts
+++ b/src/components/PluginsPanel.navigation.test.ts
@@ -51,7 +51,7 @@ vi.mock("./McpServersPanel", async () => {
vi.mock("@/lib/analytics", () => ({ track: fixture.track }));
vi.mock("./Avatar", () => ({ BotAvatar: ({ bot }: { bot: Bot }) => createElement("span", { "data-avatar": bot.id }) }));
vi.mock("./github/GithubAppCard", () => ({ GITHUB_CARD_SEARCH: "github git", GITHUB_CARD_CATEGORIES: ["Developer tools"], GithubAppCard: () => null }));
-vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => false }));
+vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => true }));
vi.mock("./XCard", () => ({
X_CARD_SEARCH: "x twitter treg tweets posts",
XCard: () => createElement("div", { "data-x-card": true }, "X (Twitter)"),
diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx
index b2e8968240..8392795f20 100644
--- a/src/components/PluginsPanel.tsx
+++ b/src/components/PluginsPanel.tsx
@@ -35,7 +35,7 @@ import { PostizCard } from "./PostizCard";
import { POSTIZ_CATALOG_CARD, POSTIZ_SEARCH } from "@/lib/postiz";
import { X_CARD_SEARCH, XCard } from "./XCard";
import { GITHUB_CARD_CATEGORIES, GITHUB_CARD_SEARCH, GithubAppCard } from "./github/GithubAppCard";
-import { useGithubConnected } from "@/lib/github-sign-in";
+import { useGithubConnected, useGithubShown } from "@/lib/github-sign-in";
import { mergeCompleteConnectorStatus, mergeCurrentConnectorStatus, onlyLatestConnectorResponses } from "@/lib/connector-status-merge";
import { openBotSettings } from "./bot-panel/panel-link";
import { openKeySettings } from "./keys/key-focus";
@@ -149,7 +149,7 @@ export function PluginsPanel() {
const [postizConnected, setPostizConnected] = useState<boolean | null>(null);
const [emailConnected, setEmailConnected] = useState<boolean | null>(null);
const [mcpServers, setMcpServers] = useState<McpServerListing[]>([]);
- const githubSignedIn = useGithubConnected();
+ const githubSignedIn = useGithubConnected(); const githubShown = useGithubShown();
const disconnectingRef = useRef<{ slug: string; label: string; account: ConnectorAccount } | null>(null);
const polls = useRef(new Map<string, () => void>());
@@ -411,7 +411,7 @@ export function PluginsPanel() {
const shownHosted = new Set(HOSTED_MCP_APPS.filter((app) => hostedShown(app, search, listing, hostedConnected)).map((app) => app.id));
const showEmail = (!search || `email mail imap smtp mailbox ${t("email.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && emailConnected !== false));
const showX = (!search || `${X_CARD_SEARCH} ${t("apps.x.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && xConnected !== false));
- const showGithub = (!search || `${GITHUB_CARD_SEARCH} ${t("githubSignIn.pitch")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && githubSignedIn === true));
+ const showGithub = githubShown && (!search || `${GITHUB_CARD_SEARCH} ${t("githubSignIn.pitch")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && githubSignedIn === true));
const showPostiz = (!search || `${POSTIZ_SEARCH} ${t("postiz.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && postizConnected !== false));
const visible = useMemo(() => (listing === "connected" ? matching.filter((card) => isConnected(card.slug)) : matching)
.map((card, index) => ({ card, index }))
@@ -745,7 +745,7 @@ export function PluginsPanel() {
)}
>
<McpServersPanel hostedCards={{ shown: (id) => !inCategoryView && shownHosted.has(id), onConnections: setHostedConnected, onServers: setMcpServers, ...(filter === "connected" ? { ownServers: { shown: ownServerShown, manage: () => chooseFilter("mcp") } } : {}) }} refreshKey={cardsRefresh} />
- <div data-native-card="github" className={githubHere && !githubSectioned ? "contents" : "hidden"}><GithubAppCard /></div>
+ <div data-native-card="github" className={githubHere && !githubSectioned ? "contents" : "hidden"}><GithubAppCard refreshKey={cardsRefresh} /></div>
<div data-native-card="x" className={showX && !inCategoryView ? "contents" : "hidden"}><XCard refreshKey={cardsRefresh} onConnection={setXConnected} /></div>
<div data-native-card="email" className={showEmail && !inCategoryView ? "contents" : "hidden"}><EmailCard refreshKey={cardsRefresh} onConnection={setEmailConnected} /></div>
<div data-native-card="postiz" className={postizHere ? "contents" : "hidden"}><PostizCard refreshKey={cardsRefresh} onConnection={setPostizConnected} /></div>
diff --git a/src/components/PluginsPanel.window.test.ts b/src/components/PluginsPanel.window.test.ts
index c8fd075507..5989d3f450 100644
--- a/src/components/PluginsPanel.window.test.ts
+++ b/src/components/PluginsPanel.window.test.ts
@@ -35,7 +35,7 @@ vi.mock("@/lib/connected-apps-cache", () => ({ readCachedInventory: () => null,
vi.mock("@/lib/product-events", () => ({ connectorConnect: vi.fn() }));
vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));
vi.mock("./github/GithubAppCard", () => ({ GITHUB_CARD_SEARCH: "github git", GITHUB_CARD_CATEGORIES: ["Developer tools"], GithubAppCard: () => null }));
-vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => false }));
+vi.mock("@/lib/github-sign-in", () => ({ useGithubConnected: () => null, useGithubShown: () => true }));
vi.mock("./XCard", async () => {
const { createElement: element } = await import("react");
return { X_CARD_SEARCH: "x", XCard: () => fixture.xTile ? element("div", { "data-app-tile": "x" }, "X") : null };
diff --git a/src/components/github/GithubAppCard.dom.test.ts b/src/components/github/GithubAppCard.dom.test.ts
index 72782e453e..f3b953d379 100644
--- a/src/components/github/GithubAppCard.dom.test.ts
+++ b/src/components/github/GithubAppCard.dom.test.ts
@@ -189,6 +189,17 @@ describe("the GitHub row in Apps", () => {
for (const spy of logs) for (const args of spy.mock.calls) expect(JSON.stringify(args)).not.toContain(token);
});
+ it("asks GitHub again when Apps' refresh is pressed, and reads again each time a card comes back into view", async () => {
+ const { calls, store } = await show({ "/api/github/sign-in": [SIGNED_OUT] });
+ expect(calls.map((call) => call.path)).toEqual(["/api/github/sign-in"]);
+ await act(async () => { root!.render(createElement(GithubAppCard, { store, refreshKey: 1 })); await Promise.resolve(); });
+ expect(calls.map((call) => call.path)).toEqual(["/api/github/sign-in", "/api/github/sign-in?check=1"]);
+ await act(async () => root!.unmount());
+ root = createRoot(host);
+ await act(async () => { root!.render(createElement(GithubAppCard, { store })); await Promise.resolve(); });
+ expect(calls).toHaveLength(3);
+ });
+
it("shows nothing at all to a person this sign-in isn't for", async () => {
await show({ "/api/github/sign-in": [new ApiError("Sign in to this team's Cloud to connect your own GitHub.", 403)] });
expect(host.innerHTML).toBe("");
diff --git a/src/components/github/GithubAppCard.tsx b/src/components/github/GithubAppCard.tsx
index a2b29f033f..bd1553921f 100644
--- a/src/components/github/GithubAppCard.tsx
+++ b/src/components/github/GithubAppCard.tsx
@@ -1,3 +1,4 @@
+import { useEffect } from "react";
import { Check, Loader2 } from "lucide-react";
import { githubSignIn, useGithubSignIn, type GithubSignInStore, type GithubSignInView } from "@/lib/github-sign-in";
@@ -43,8 +44,9 @@ export function GithubRowAction({ view, store, className = PILL }: { view: Githu
/** GitHub in Apps: the server's own sign-in, which bots' git and pull requests use. Nothing shows for a person who may
* not manage it. */
-export function GithubAppCard({ store = githubSignIn }: { store?: GithubSignInStore }) {
+export function GithubAppCard({ store = githubSignIn, refreshKey = 0 }: { store?: GithubSignInStore; refreshKey?: number }) {
const view = useGithubSignIn(store);
+ useEffect(() => { if (refreshKey > 0) void store.refresh(true); }, [store, refreshKey]);
if (view.phase === "hidden") return null;
const state = view.status?.state ?? "loading";
const signedIn = state === "signed-in";
diff --git a/src/components/github/GithubChatCard.dom.test.ts b/src/components/github/GithubChatCard.dom.test.ts
index 16885ff4ca..790606a123 100644
--- a/src/components/github/GithubChatCard.dom.test.ts
+++ b/src/components/github/GithubChatCard.dom.test.ts
@@ -84,3 +84,21 @@ it("shows nothing to someone whose sign-in it isn't, and nothing once set aside"
await show([SIGNED_OUT], message("required", { dismissed: true }));
expect(host.innerHTML).toBe("");
});
+
+it("asks again before it says connected: a sign-in revoked since Apps last looked shows Connect again", async () => {
+ const answers: GithubSignInStatus[] = [{ state: "signed-in", login: "octo", source: "mausbot", scopes: [], checkedAt: 1 }];
+ const store = createGithubSignInStore({ api: async () => answers[0], timers: { set: () => null, clear: () => {} } });
+ const appsStillOpen = store.subscribe(() => {});
+ await act(async () => { await Promise.resolve(); });
+ expect(store.snapshot().status?.state).toBe("signed-in");
+ answers[0] = { state: "invalid", login: "octo", source: "mausbot", reason: "revoked" };
+ const { GithubChatCard } = await import("./GithubChatCard");
+ root = createRoot(host);
+ await act(async () => { root!.render(createElement(GithubChatCard, { botId: "chief", threadId: "t1", message: message(), store })); });
+ await act(async () => { await Promise.resolve(); await Promise.resolve(); });
+ expect(host.querySelector("[data-ask-card='settled']")).toBeNull();
+ expect(button("Connect again")).toBeTruthy();
+ expect(host.textContent).toContain("GitHub sign-in stopped working.");
+ expect(sent.some((call) => call.path.includes("/status"))).toBe(false);
+ appsStillOpen();
+});
diff --git a/src/components/github/GithubChatCard.tsx b/src/components/github/GithubChatCard.tsx
index 998cd00dcb..3e173d6a5f 100644
--- a/src/components/github/GithubChatCard.tsx
+++ b/src/components/github/GithubChatCard.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { githubSignIn, useGithubSignIn, type GithubSignInStore } from "@/lib/github-sign-in";
@@ -18,9 +18,17 @@ export function GithubChatCard({ botId, color, threadId, message, store = github
}) {
const connector = message.connector!;
const view = useGithubSignIn(store);
- const signedIn = view.status?.state === "signed-in" ? view.status : null;
+ // What another card or Apps read earlier may be out of date: this card asks again before it says connected.
+ const [checked, setChecked] = useState(false);
+ const signedIn = checked && view.status?.state === "signed-in" ? view.status : null;
const endpoint = `/api/bots/${encodeURIComponent(botId)}/connector-cards/${encodeURIComponent(message.id)}`;
const settling = useRef(false);
+ useEffect(() => {
+ if (connector.status === "connected" || connector.dismissed) return;
+ let live = true;
+ void store.refresh().finally(() => { if (live) setChecked(true); });
+ return () => { live = false; };
+ }, [store, connector.status, connector.dismissed]);
useEffect(() => {
if (!signedIn || connector.status === "connected" || connector.dismissed || settling.current) return;
@@ -39,7 +47,7 @@ export function GithubChatCard({ botId, color, threadId, message, store = github
);
}
- const state = view.status?.state;
+ const state = checked ? view.status?.state : undefined;
const dismiss = () => void api(`${endpoint}/dismiss`, { method: "POST", body: JSON.stringify({ threadId }) }).catch(() => {});
const spinner = <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" />;
return (
@@ -47,7 +55,7 @@ export function GithubChatCard({ botId, color, threadId, message, store = github
ariaLabel={connector.label}
icon={<GithubMark className="size-4 rounded-[4px]" />}
title={message.text}
- explanation={view.phase === "ready" ? githubHeadline(view) : undefined}
+ explanation={checked && view.phase === "ready" ? githubHeadline(view) : undefined}
onDismiss={dismiss}
dismissLabel={t("connectors.card.notNow")}
footer={
@@ -61,10 +69,10 @@ export function GithubChatCard({ botId, color, threadId, message, store = github
<button type="button" data-github-connect disabled={view.busy !== null} onClick={() => void store.start()} {...askPrimary(color)}>
{view.busy === "start" ? spinner : t(state === "invalid" ? "githubSignIn.connectAgain" : "githubSignIn.connectGithub")}
</button>
- ) : view.phase === "loading" ? spinner : null
+ ) : !checked || view.phase === "loading" ? spinner : null
}
>
- {view.phase === "ready" && <GithubSignInDetails view={view} store={store} />}
+ {checked && view.phase === "ready" && <GithubSignInDetails view={view} store={store} />}
</AskCard>
);
}
diff --git a/src/lib/github-sign-in.ts b/src/lib/github-sign-in.ts
index 0664fcaaeb..0489f0ead5 100644
--- a/src/lib/github-sign-in.ts
+++ b/src/lib/github-sign-in.ts
@@ -65,7 +65,6 @@ export function createGithubSignInStore(deps: { api?: Api; timers?: Timers } = {
const api: Api = deps.api ?? storeApi;
const timers: Timers = deps.timers ?? { set: (fn, ms) => setTimeout(fn, ms), clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>) };
let view = INITIAL;
- let loaded = false;
let reads = 0;
let timer: unknown = null;
const listeners = new Set<() => void>();
@@ -113,7 +112,7 @@ export function createGithubSignInStore(deps: { api?: Api; timers?: Timers } = {
try {
const answer = await api(`${GITHUB_SIGN_IN_PATH}/${action}`, { method: "POST", ...(body === undefined ? {} : { body }) });
if (!isStatus(answer)) throw new Error("unexpected GitHub sign-in status");
- set({ phase: "ready", status: answer, busy: null, refused: answer.state === "signed-in" ? false : view.refused });
+ set({ phase: "ready", status: answer, busy: null, refused: action === "start" || answer.state === "signed-in" ? false : view.refused });
return true;
} catch (cause) {
const status = statusOf(cause);
@@ -132,11 +131,10 @@ export function createGithubSignInStore(deps: { api?: Api; timers?: Timers } = {
return {
subscribe(listener: () => void): () => void {
+ // Each time a card comes into view after none was, the answer is asked for again: a sign-in can change elsewhere.
+ const first = listeners.size === 0;
listeners.add(listener);
- if (!loaded) {
- loaded = true;
- void read();
- }
+ if (first) void read();
schedule();
return () => {
listeners.delete(listener);