Skip to content

m365-copilot login always fails after a successful sign-in: window.__staticRouterHydrationData is gone by the time the web-session check runs #8991

Closed

Description

@neomaitre

Client or integration

Direct HTTP/API client

Area

Authentication and account pool

Summary

ocx account login m365-copilot never completes for an account with a Microsoft 365 Copilot licence.
The Microsoft sign-in and the authorization-code callback succeed, and the Chrome window OpenCodex opens ends on
the Copilot chat page, signed in. About two minutes later the flow ends with the generic
OAuth authentication failed. Check the OpenCodex account status and retry. and nothing is written to
auth.json. The underlying error is:

Microsoft 365 Copilot web sign-in did not expose a work-account model picker; retry login

Expected: the web session is captured, the credential is stored and the provider is registered.

Cause (as far as we can tell): readM365BrowserWebSession in src/oauth/m365-copilot-web-session.ts polls
window.__staticRouterHydrationData in the live page with Runtime.evaluate. The Copilot web app reads that
global during hydration and then removes it, and the inline script that defined it is no longer in the DOM. The
check therefore never sees the account or model-picker data, although the server HTML still contains both.

Suggested fix. Read the account from the server HTML instead of the hydrated window, reusing the parser the
model discovery path already uses (parseM365ModelBootstrap in src/providers/m365-copilot-discovery.ts, which
parses the same window.__staticRouterHydrationData = JSON.parse("...") block from fetched HTML). A local patch
along these lines fixed login on the first attempt, and the resulting auth.json then worked unchanged on a stock
2.100.6 build (model discovery and chat):

// src/oauth/m365-copilot-web-session.ts (sketch)
import { M365_COPILOT_WEB_URL, M365_COPILOT_WEB_COOKIE_NAMES, normalizeM365WebSession, parseM365ModelBootstrap } from "../providers/m365-copilot-discovery";

const FETCH_CHAT_HTML = "fetch(location.origin + '/chat/', { credentials: 'include' }).then(r => r.ok ? r.text() : '')";

export async function readM365BrowserWebSession(browser: BrowserCommands, context: string, signal: AbortSignal): Promise<M365CopilotWebSession> {
  await browser.command("Page.navigate", { url: M365_COPILOT_WEB_URL }, context);
  const deadline = Date.now() + 120_000;
  while (Date.now() < deadline) {
    signal.throwIfAborted();
    const result = await browser.command("Runtime.evaluate", { expression: FETCH_CHAT_HTML, awaitPromise: true, returnByValue: true }, context).catch(() => null);
    const html = result?.result?.value;
    let accountId = "";
    if (typeof html === "string" && html) {
      try { accountId = parseM365ModelBootstrap(html).accountId; } catch { /* not ready yet */ }
    }
    if (accountId) {
      const { cookies } = await browser.command("Network.getCookies", { urls: [M365_COPILOT_WEB_URL] }, context);
      const cookie = /* unchanged cookie filter */;
      const session = normalizeM365WebSession({ cookie, accountId });
      if (session) return session;
    }
    await Bun.sleep(1_000);
  }
  throw new Error("Microsoft 365 Copilot web sign-in did not expose a work-account model picker; retry login");
}

Alternatives: keep the window probe as a fast path and fall back to the HTML fetch; or read the cookies first
and fetch the HTML from the proxy side with providerOutboundGet, as fetchM365ModelRoster already does. Both
keep the existing account-mismatch check in loginM365Copilot meaningful, since the account still comes from the
page the user signed into.

A second, smaller request: the flow status only returns the generic OAuth authentication failed message, and
nothing reaches the proxy log, so the cause was invisible without patching the source. A debug-level log line
with only the error class and message (no tokens, cookies, account ids or credential payloads) in settle() of
src/oauth/index.ts would have saved most of the diagnosis.

Reproduction

  1. ocx start on a desktop machine with Chrome installed.
  2. ocx account login m365-copilot (we also tried --no-wait and polling /api/oauth/status; same result).
  3. Sign in with a Microsoft 365 Copilot-licensed account and complete the sign-in challenge in the window OpenCodex
    opens.
  4. The window lands on https://copilot.cloud.microsoft/chat/, signed in, and shows the chat UI and model
    picker.
  5. After the 120 s deadline in readM365BrowserWebSession, the flow ends with status: error and no
    credential is stored.

Reproduced three times in a row with fresh temporary browser profiles.

What we measured inside the signed-in page at the moment of failure, by adding temporary logging to a local
copy (booleans and names only):

Probe Result
location copilot.cloud.microsoft/chat/
window.__staticRouterHydrationData present false (so loaderData.root, store.accountInfo and __queryState.queries are all absent)
document.documentElement.outerHTML contains __staticRouterHydrationData false
fetch(location.origin + '/chat/', {credentials: 'include'}) 200, about 385 KB
...response text contains __staticRouterHydrationData / accountInfo / modelSelectorMetadata true / true / true
Cookies for copilot.cloud.microsoft matching M365_COPILOT_WEB_COOKIE_NAMES present (OhpAuth, OhpToken, SSRUserType)

So the session and the data are there; only the place the check looks for them is empty.

Version

2.100.6 (also the current npm latest at the time of writing)

Operating system

Linux: proxy under Bun 1.4.4; browser Google Chrome 156 on Ubuntu 24.04 (X11)

Provider and model

m365-copilot / Magic (login flow; fails before any model is used)

Logs or error output

# GET /api/oauth/status?provider=m365-copilot&flowId=<id>, while signing in, then after the deadline
{"done": false, "status": "pending"}
{"done": true, "status": "error", "error": "OAuth authentication failed. Check the OpenCodex account status and retry."}

# raw error, from a temporary console.error(err.name, err.message) in settle() (class and message only)
Error Microsoft 365 Copilot web sign-in did not expose a work-account model picker; retry login

Screenshots and supporting files

None attached. Happy to run further probes.

Additional context (not part of this bug; for awareness)

  • With a working login, plain chat works on every model the roster lists. Tool
    calls do not: with tools (and with tool_choice set to required or to a named function), Magic and
    Gpt_5_6_Chat reply in prose saying the tool is not available, and Claude_Sonnet returns
    502 upstream_server_error. That looks like a separate, provider-side limit of prompt-emulated tools; we can
    open a separate issue if useful.

Redacted configuration

Checks

  • I searched existing issues and documentation.
  • I removed secrets, tokens, account details, request credentials, and personal data.

Activity

  1. added
    bug
    on Nov 20, 2026
  2. added
    account-pool
    on Nov 20, 2026
  3. coderabbitai commented on Nov 20, 2026

    @coderabbitai
    Contributor
    🔗 Related PRs

    #7757 - feat(providers): add M365 Copilot with live account model discovery [merged]


    📝 Issue Planner

    Check the box below or use the @coderabbitai plan command to generate an implementation plan and prompts that you can use with your favorite coding assistant.

    • Create Plan

    🧪 Issue enrichment is currently in open beta.

    To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

    issue_enrichment:
      auto_enrich:
        enabled: false

    💬 Have feedback or questions? Drop into our discord!

  4. lidge-jun commented on Nov 20, 2026

    @lidge-jun
    Owner

    Fixed by #8994, squash-merged into dev as a17ff4d.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    account-poolbug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions