Python
Fix Slack connect dead-ending on "not signed in" for expired cloud sessions
Nabil hassan mohamed ali97be4ab91146
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex 37508240..cf2462b1 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -982,7 +982,7 @@ export async function cloudLogout(): Promise<{ ok: boolean }> {export async function connectManaged(name: string,options?: { access?: "read" | "write"; flow?: "install" },-): Promise<{ ok: boolean; error?: string }> {+): Promise<{ ok: boolean; error?: string; signed_in?: boolean }> {const res = await fetch(`${httpBase()}/v1/connectors/${encodeURIComponent(name)}/connect-managed`,{diff --git a/surfaces/gui/src/components/connectors/AddConnectionModal.slack.test.tsx b/surfaces/gui/src/components/connectors/AddConnectionModal.slack.test.tsxnew file mode 100644index 00000000..f852bb94--- /dev/null+++ b/surfaces/gui/src/components/connectors/AddConnectionModal.slack.test.tsx@@ -0,0 +1,160 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen, waitFor, fireEvent } from "@testing-library/react";++// issue #658 — "Add to Slack" dead-ended on a bare "not signed in" when the+// cloud-status poll still said signed_in:true but the session had actually+// expired (begin_managed_connect is the authoritative check and correctly+// rejects it). The fix: recover into the sign-in flow instead of leaving a+// dead error, then automatically resume the Slack connect once signed in.++const connectManaged =+ vi.fn<(name: string, options?: { access?: "read" | "write" }) => Promise<{ ok: boolean; error?: string; signed_in?: boolean }>>();+const cloudLogin = vi.fn<() => Promise<{ ok: boolean }>>(async () => ({ ok: true }));+let signInDone: ((s: { signed_in: boolean; account: string; user_id: string } | null) => void) | null = null;+const waitForCloudSignIn = vi.fn((onDone: (s: { signed_in: boolean; account: string; user_id: string } | null) => void) => {+ signInDone = onDone;+ return () => {+ signInDone = null;+ };+});+const announceCloudChanged = vi.fn();++vi.mock("../../api", () => ({+ connectConnector: vi.fn(),+ connectManaged: (name: string, options?: { access?: "read" | "write" }) => connectManaged(name, options),+ connectMcpBacked: vi.fn(),+ getConnectors: vi.fn(async () => []),+ cloudLogin: () => cloudLogin(),+ waitForCloudSignIn: (onDone: (s: { signed_in: boolean; account: string; user_id: string } | null) => void) =>+ waitForCloudSignIn(onDone),+ announceCloudChanged: () => announceCloudChanged(),+}));++import { AddConnectionModal } from "./AddConnectionModal";+import type { Connector } from "../../api";++const slackConnector = (): Connector => ({+ name: "slack",+ title: "Slack",+ icon: "slack",+ blurb: "",+ auth: "oauth",+ two_way: true,+ channels: true,+ available: true,+ fields: [],+ instructions: [],+ connected: false,+ account: null,+ enabled: true,+ brand_color: "#611f69",+ logo: "slack",+ allowed_users: [],+ tools: [],+ managed: true,+ managed_profile: false,+});++afterEach(() => {+ cleanup();+ connectManaged.mockReset();+ cloudLogin.mockClear();+ waitForCloudSignIn.mockClear();+ announceCloudChanged.mockClear();+ signInDone = null;+});++describe("AddConnectionModal — Slack one-click (issue #658)", () => {+ it("shows the Add to Slack button when the cloud status says signed in", () => {+ render(+ <AddConnectionModal+ c={slackConnector()}+ cloud={{ signed_in: true, account: "[email protected]", user_id: "u1" }}+ onClose={vi.fn()}+ onChanged={vi.fn()}+ />,+ );+ expect(screen.getByTestId("modal-add-to-slack")).toBeTruthy();+ expect(screen.queryByTestId("inline-cloud-sign-in")).toBeNull();+ });++ it("a stale signed-in status: connect rejects as not-signed-in, and the pane recovers into sign-in instead of dead-ending", async () => {+ // Frontend still thinks it's signed in (last poll), but the session actually+ // expired — begin_managed_connect's fresh_access_token check fails server-side.+ connectManaged.mockResolvedValueOnce({ ok: false, error: "not signed in", signed_in: false });+ render(+ <AddConnectionModal+ c={slackConnector()}+ cloud={{ signed_in: true, account: "[email protected]", user_id: "u1" }}+ onClose={vi.fn()}+ onChanged={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("modal-add-to-slack"));+ await waitFor(() => expect(connectManaged).toHaveBeenCalledWith("slack", undefined));+ // No dead-end: a real sign-in button appears, not just inert red text.+ await waitFor(() => expect(screen.getByTestId("inline-cloud-sign-in")).toBeTruthy());+ expect(screen.queryByText("not signed in")).toBeNull();+ });++ it("signing back in from the recovered pane automatically resumes the Slack connect", async () => {+ connectManaged+ .mockResolvedValueOnce({ ok: false, error: "not signed in", signed_in: false })+ .mockResolvedValueOnce({ ok: true });+ render(+ <AddConnectionModal+ c={slackConnector()}+ cloud={{ signed_in: true, account: "[email protected]", user_id: "u1" }}+ onClose={vi.fn()}+ onChanged={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("modal-add-to-slack"));+ await waitFor(() => expect(screen.getByTestId("inline-cloud-sign-in")).toBeTruthy());++ fireEvent.click(screen.getByTestId("inline-cloud-sign-in"));+ await waitFor(() => expect(cloudLogin).toHaveBeenCalled());+ await waitFor(() => expect(waitForCloudSignIn).toHaveBeenCalled());++ // The browser sign-in lands; the poll callback fires with the fresh status.+ signInDone?.({ signed_in: true, account: "[email protected]", user_id: "u1" });++ // Slack connect is retried on its own — the user never re-clicks anything.+ await waitFor(() => expect(connectManaged).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.getByTestId("modal-add-to-slack")).toBeTruthy());+ expect(screen.getByTestId("modal-add-to-slack").textContent).toMatch(/browser/i);+ });++ it("a genuine sign-in error (not a session-expiry) still surfaces as an error, not a sign-in prompt", async () => {+ connectManaged.mockResolvedValueOnce({ ok: false, error: "cloud unreachable" });+ render(+ <AddConnectionModal+ c={slackConnector()}+ cloud={{ signed_in: true, account: "[email protected]", user_id: "u1" }}+ onClose={vi.fn()}+ onChanged={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("modal-add-to-slack"));+ await waitFor(() => expect(screen.getByText("cloud unreachable")).toBeTruthy());+ expect(screen.queryByTestId("inline-cloud-sign-in")).toBeNull();+ });++ it("signed out from the start: sign-in also auto-continues into the Slack connect", async () => {+ connectManaged.mockResolvedValueOnce({ ok: true });+ render(+ <AddConnectionModal+ c={slackConnector()}+ cloud={{ signed_in: false, account: "", user_id: "" }}+ onClose={vi.fn()}+ onChanged={vi.fn()}+ />,+ );+ expect(screen.getByTestId("inline-cloud-sign-in")).toBeTruthy();+ fireEvent.click(screen.getByTestId("inline-cloud-sign-in"));+ await waitFor(() => expect(waitForCloudSignIn).toHaveBeenCalled());+ signInDone?.({ signed_in: true, account: "[email protected]", user_id: "u1" });+ await waitFor(() => expect(connectManaged).toHaveBeenCalledWith("slack", undefined));+ await waitFor(() => expect(screen.getByTestId("modal-add-to-slack").textContent).toMatch(/browser/i));+ });+});diff --git a/surfaces/gui/src/components/connectors/AddConnectionModal.tsx b/surfaces/gui/src/components/connectors/AddConnectionModal.tsxindex 25114a82..beeeaf19 100644--- a/surfaces/gui/src/components/connectors/AddConnectionModal.tsx+++ b/surfaces/gui/src/components/connectors/AddConnectionModal.tsx@@ -219,10 +219,17 @@ function SlackOneClick({ c, cloud }: { c: Connector; cloud: CloudStatus | null }const { t: tt } = useTranslation();const [waiting, setWaiting] = useState(false);const [error, setError] = useState<string | null>(null);+ // The cloud-status poll runs every 5s (ConnectorsSection), so `cloud.signed_in`+ // can still say true for a few seconds after the session actually expired.+ // "Add to Slack" then dead-ended on a bare "not signed in" (issue #658) instead+ // of recovering — this flag switches the pane to sign-in once the connect+ // attempt itself (the authoritative check) says the session isn't usable.+ const [sessionExpired, setSessionExpired] = useState(false);const go = async () => {setError(null);const res = await connectManaged(c.name);if (res.ok) setWaiting(true);+ else if (res.signed_in === false) setSessionExpired(true);else setError(res.error || tt("modal.could_not_start_install"));};return (@@ -230,12 +237,22 @@ function SlackOneClick({ c, cloud }: { c: Connector; cloud: CloudStatus | null }<p className="text-ui text-muted">{tt("modal.slack_blurb")}</p>- {cloud?.signed_in ? (- <button className={PILL_ACCENT + " w-full !py-2"} data-testid="modal-add-to-slack" onClick={go} disabled={waiting}>- {waiting ? tt("cloud.check_browser") : tt("modal.add_to_slack")}+ {waiting ? (+ // The sign-in retry (if any) already happened — always land here once+ // connectManaged has actually succeeded, so a just-completed sign-in+ // doesn't flash the "Sign in" button again while Slack's own consent+ // tab is open.+ <button className={PILL_ACCENT + " w-full !py-2"} data-testid="modal-add-to-slack" disabled>+ {tt("cloud.check_browser")}+ </button>+ ) : sessionExpired ? (+ <CloudSignInInline onSignedIn={go} />+ ) : cloud?.signed_in ? (+ <button className={PILL_ACCENT + " w-full !py-2"} data-testid="modal-add-to-slack" onClick={go}>+ {tt("modal.add_to_slack")}</button>) : cloud ? (- <CloudSignInInline />+ <CloudSignInInline onSignedIn={go} />) : (<CloudStatusPending />)}diff --git a/surfaces/gui/src/components/connectors/CloudSignIn.tsx b/surfaces/gui/src/components/connectors/CloudSignIn.tsxindex febec650..6247b2aa 100644--- a/surfaces/gui/src/components/connectors/CloudSignIn.tsx+++ b/surfaces/gui/src/components/connectors/CloudSignIn.tsx@@ -8,7 +8,17 @@ import { announceCloudChanged, cloudLogin, waitForCloudSignIn } from "../../api"// even poll-less hosts (the Sources rail's inline pane) re-render signed in —// relying on "some other section's 5s poll" left the rail stuck on the prompt// (FB-013).-export function CloudSignInInline({ blurb }: { blurb?: string }) {+export function CloudSignInInline({+ blurb,+ onSignedIn,+}: {+ blurb?: string;+ // Fires once the poll confirms sign-in landed, after announceCloudChanged() —+ // lets a caller (e.g. a one-click connect that just discovered its session had+ // expired) resume the flow it was in instead of leaving the user to notice the+ // button reappeared and click it again (issue #658).+ onSignedIn?: () => void;+}) {const { t } = useTranslation();const [waiting, setWaiting] = useState(false);const cancelRef = useRef<(() => void) | null>(null);@@ -24,7 +34,10 @@ export function CloudSignInInline({ blurb }: { blurb?: string }) {cancelRef.current?.();cancelRef.current = waitForCloudSignIn((s) => {setWaiting(false);- if (s?.signed_in) announceCloudChanged();+ if (s?.signed_in) {+ announceCloudChanged();+ onSignedIn?.();+ }});}}>diff --git a/tests/test_cloud.py b/tests/test_cloud.pyindex 2c5c2640..43214702 100644--- a/tests/test_cloud.py+++ b/tests/test_cloud.py@@ -236,6 +236,28 @@ def test_begin_managed_connect_requires_sign_in(secrets, config):out = cloud.begin_managed_connect(secrets, config, "gmail")assert not out["ok"]assert "not signed in" in out["error"]+ assert out["signed_in"] is False+++def test_begin_managed_connect_reports_signed_out_on_expired_unrefreshable_session(+ secrets, config+):+ """GitHub issue #658 ("Add to Slack" dead-ends on "not signed in"): the GUI+ polls /v1/cloud/status every 5s and only checks `access_token` presence+ (cloud.status), so a stored-but-expired session with no refresh_token still+ reads signed_in=True there — the button stays live. begin_managed_connect is+ the flow's actual authority: it calls fresh_access_token, which returns None+ for exactly this profile, so this is where the rejection has to happen and+ where the GUI's recovery-into-sign-in depends on `signed_in: False` being set+ (not just `ok: False`, whose text a UI shouldn't have to pattern-match)."""+ secrets.put(+ cloud.CLOUD_AUTH_PROFILE,+ {"access_token": "stale", "expires": time.time() - 10}, # no refresh_token+ )+ assert cloud.status(secrets)["signed_in"] is True # the stale, misleading read++ out = cloud.begin_managed_connect(secrets, config, "slack")+ assert out == {"ok": False, "error": "not signed in", "signed_in": False}def test_managed_profile_is_field_compatible_with_manual(secrets):diff --git a/tests/test_cloud_server.py b/tests/test_cloud_server.pyindex e3c8a678..451272e4 100644--- a/tests/test_cloud_server.py+++ b/tests/test_cloud_server.py@@ -47,6 +47,27 @@ def test_connect_managed_requires_sign_in(client):assert "not signed in" in body["error"]+def test_connect_managed_reports_signed_in_false_on_expired_session(client, monkeypatch):+ """GitHub issue #658: /v1/cloud/status can still say signed_in=True from a+ stale-but-present access_token (cloud.status only checks presence, not+ freshness) while the actual connect attempt — which needs a token it can use+ right now — correctly fails. The GUI (AddConnectionModal's SlackOneClick)+ relies on this route's `signed_in: False` to recover into a sign-in prompt+ instead of dead-ending on the bare error text."""+ import time++ from coworker import cloud++ client.manager.secrets.put(+ cloud.CLOUD_AUTH_PROFILE,+ {"access_token": "stale", "expires": time.time() - 10}, # no refresh_token+ )+ assert client.get("/v1/cloud/status").json()["signed_in"] is True++ body = client.post("/v1/connectors/slack/connect-managed").json()+ assert body == {"ok": False, "error": "not signed in", "signed_in": False}++def test_oauth_callback_writes_profile_and_returns_page(client):_allow_managed_state()resp = client.post(