From b715d447dbeeb41a67429bd64d851763fea71fb8 Mon Sep 17 00:00:00 2001 From: "Angnuo Li (from Dev Box)" Date: Mon, 16 Nov 2026 16:49:46 +0800 Subject: [PATCH] feat(copilot): add staged sign-in timing diagnostics --- desktop/src/github-copilot-auth-worker.ts | 191 +++++++++++++- desktop/src/github-copilot-auth.ts | 70 ++++- .../src/github-copilot-login-timing.test.ts | 240 ++++++++++++++++++ desktop/src/main.ts | 2 + docs/reference/github-copilot-login-timing.md | 28 ++ 5 files changed, 525 insertions(+), 6 deletions(-) create mode 100644 desktop/src/github-copilot-login-timing.test.ts create mode 100644 docs/reference/github-copilot-login-timing.md diff --git a/desktop/src/github-copilot-auth-worker.ts b/desktop/src/github-copilot-auth-worker.ts index 6617bca..d79a380 100644 --- a/desktop/src/github-copilot-auth-worker.ts +++ b/desktop/src/github-copilot-auth-worker.ts @@ -1,12 +1,158 @@ import { pathToFileURL } from "node:url"; import * as path from "node:path"; import * as fs from "node:fs"; +import { channel } from "node:diagnostics_channel"; +import { performance } from "node:perf_hooks"; const MESSAGE_PREFIX = "MICROCLAW_COPILOT_AUTH:"; const GITHUB_DEVICE_URL = "https://github.com/login/device"; // This worker is packaged as a standalone extraResource, so it cannot import app.asar modules. export const GITHUB_COPILOT_AUTH_AGENT_ID = "main"; +const TIMING_PHASES = [ + "worker-ready", + "sdk-import", + "config-read", + "provider-prepare", + "auth-flow", + "device-code-http", + "device-code-ready", + "authorization-and-model-check", + "credential-save-and-refresh", +] as const; +type TimingPhase = (typeof TIMING_PHASES)[number]; +type TimingStatus = "started" | "success" | "error" | "cancelled"; +export interface GitHubCopilotWorkerTiming { + type: "timing"; + phase: TimingPhase; + status: TimingStatus; + elapsedMs: number; + durationMs?: number; + attempt?: number; + httpStatus?: number; +} + +/** Timing frames accept only known labels and numbers, never SDK text or credentials. */ +export function parseGitHubCopilotWorkerTiming( + value: Record, +): GitHubCopilotWorkerTiming | undefined { + if ( + !TIMING_PHASES.includes(value.phase as TimingPhase) || + typeof value.status !== "string" || + !["started", "success", "error", "cancelled"].includes(value.status) + ) + return; + const result: GitHubCopilotWorkerTiming = { + type: "timing", + phase: value.phase as TimingPhase, + status: value.status as TimingStatus, + elapsedMs: 0, + }; + for (const key of ["elapsedMs", "durationMs", "attempt", "httpStatus"] as const) { + const number = value[key]; + if (number === undefined && key !== "elapsedMs") continue; + if (typeof number !== "number" || !Number.isSafeInteger(number) || number < 0) return; + result[key] = number; + } + return result; +} + +export class GitHubCopilotLoginTiming { + private readonly startedAt: number; + private readonly pending = new Set<(status: TimingStatus) => void>(); + constructor( + private readonly emit: (timing: GitHubCopilotWorkerTiming) => void, + private readonly now = () => performance.now(), + ) { + this.startedAt = now(); + } + + private report(event: Omit): void { + try { + this.emit({ + type: "timing", + ...event, + elapsedMs: Math.max(0, Math.round(this.now() - this.startedAt)), + }); + } catch { + /* Diagnostics must not change authentication outcomes. */ + } + } + + mark(phase: TimingPhase): void { + this.report({ phase, status: "success", durationMs: 0 }); + } + + begin(phase: TimingPhase, attempt?: number) { + const startedAt = this.now(); + let finished = false; + const finish = (status: TimingStatus = "success", httpStatus?: number) => { + if (finished) return; + finished = true; + this.pending.delete(finish); + this.report({ + phase, + status, + durationMs: Math.max(0, Math.round(this.now() - startedAt)), + ...(attempt === undefined ? {} : { attempt }), + ...(httpStatus === undefined ? {} : { httpStatus }), + }); + }; + this.pending.add(finish); + this.report({ phase, status: "started", ...(attempt === undefined ? {} : { attempt }) }); + return finish; + } + + finish(status: TimingStatus): void { + for (const finish of [...this.pending]) finish(status); + } +} + +/** Observe transport boundaries without replacing fetch or reading request/response bodies. */ +export function observeGitHubDeviceCodeRequests(timing: GitHubCopilotLoginTiming): () => void { + type Request = { origin?: unknown; path?: unknown }; + type Payload = { request?: Request; response?: { statusCode?: number } }; + const requests = new WeakMap< + Request, + { finish: ReturnType; status?: number } + >(); + let attempts = 0; + const handlers: Record void> = { + "undici:request:create": ({ request }) => { + if (request?.origin !== "https://github.com" || request.path !== "/login/device/code") return; + requests.set(request, { finish: timing.begin("device-code-http", ++attempts) }); + }, + "undici:request:headers": ({ request, response }) => { + const active = request && requests.get(request); + if (active && Number.isInteger(response?.statusCode)) active.status = response!.statusCode; + }, + "undici:request:trailers": ({ request }) => { + const active = request && requests.get(request); + if (active) + active.finish( + active.status !== undefined && active.status >= 400 ? "error" : "success", + active.status, + ); + }, + "undici:request:error": ({ request }) => { + if (request) requests.get(request)?.finish("error"); + }, + }; + const subscriptions = Object.entries(handlers).map(([name, handler]) => { + const listener = (payload: unknown) => { + try { + handler(payload as Payload); + } catch { + /* Observation must not affect HTTP. */ + } + }; + const target = channel(name); + target.subscribe(listener); + return () => target.unsubscribe(listener); + }); + return () => subscriptions.forEach((unsubscribe) => unsubscribe()); +} + interface AuthRuntimeModule { runModelsAuthLoginFlow(options: Record): Promise<{ profiles?: Array<{ profileId?: string }>; @@ -111,6 +257,7 @@ export function buildGitHubCopilotLoginOptions(params: { openUrl: (url: string) => Promise; runtime: Record; signal?: AbortSignal; + beforePersistentEffect?: () => void; }): Record { return { config: params.config, @@ -121,6 +268,9 @@ export function buildGitHubCopilotLoginOptions(params: { prompter: params.prompter, openUrl: params.openUrl, runtime: params.runtime, + ...(params.beforePersistentEffect + ? { beforePersistentEffect: params.beforePersistentEffect } + : {}), ...(params.signal ? { signal: params.signal, @@ -130,7 +280,7 @@ export function buildGitHubCopilotLoginOptions(params: { }; } -async function main(signal: AbortSignal): Promise { +async function main(signal: AbortSignal, timing: GitHubCopilotLoginTiming): Promise { const runtimePath = process.argv[2]; const operation = process.argv[3] ?? "login"; if (!runtimePath) throw new Error("OpenClaw provider authentication runtime was not provided"); @@ -143,11 +293,13 @@ async function main(signal: AbortSignal): Promise { ) => Promise; const providerCatalogPath = path.join(path.dirname(runtimePath), "provider-catalog-runtime.js"); const configRuntimePath = resolveGitHubCopilotConfigRuntimePath(path.dirname(runtimePath)); + const imported = timing.begin("sdk-import"); const [authRuntime, providerCatalogRuntime, configRuntime] = await Promise.all([ dynamicImport(pathToFileURL(runtimePath).href), dynamicImport(pathToFileURL(providerCatalogPath).href), dynamicImport(pathToFileURL(configRuntimePath).href), ]); + imported(); signal.throwIfAborted(); if (typeof authRuntime.runModelsAuthLoginFlow !== "function") { throw new Error("OpenClaw provider authentication runtime is incompatible"); @@ -156,7 +308,10 @@ async function main(signal: AbortSignal): Promise { throw new Error("OpenClaw provider catalog runtime is incompatible"); } + const configured = timing.begin("config-read"); const config = enableGitHubCopilotPlugin(readGitHubCopilotRuntimeConfig(configRuntime)); + configured(); + const prepared = timing.begin("provider-prepare"); const providers = providerCatalogRuntime.resolvePluginProviders({ config, mode: "setup", @@ -169,17 +324,26 @@ async function main(signal: AbortSignal): Promise { if (!providers.some((provider) => provider.id === "github-copilot")) { throw new Error("The bundled GitHub Copilot provider is unavailable"); } + prepared(); const unsupportedPrompt = async (): Promise => { throw new Error("GitHub Copilot requested an unsupported interactive prompt"); }; let emptyProfileOutcome: "cancelled" | "expired" | null = null; + let awaitingAuthorization: ReturnType | undefined; + let persisted: ReturnType | undefined; const prompter = { intro: async () => {}, outro: async () => {}, note: async (message: string) => { const prompt = extractDevicePrompt(message); - if (prompt) send({ type: "device-code", ...prompt }); + if (prompt) { + if (!awaitingAuthorization) { + timing.mark("device-code-ready"); + awaitingAuthorization = timing.begin("authorization-and-model-check"); + } + send({ type: "device-code", ...prompt }); + } if (message.includes("login was cancelled")) emptyProfileOutcome = "cancelled"; if (message.includes("device code expired")) emptyProfileOutcome = "expired"; }, @@ -193,11 +357,16 @@ async function main(signal: AbortSignal): Promise { }), }; + const authenticated = timing.begin("auth-flow"); const result = await authRuntime.runModelsAuthLoginFlow( buildGitHubCopilotLoginOptions({ signal, config, prompter, + beforePersistentEffect: () => { + awaitingAuthorization?.(); + persisted ??= timing.begin("credential-save-and-refresh"); + }, openUrl: async (url: string) => send({ type: "open-url", url }), runtime: { log: () => {}, @@ -211,12 +380,18 @@ async function main(signal: AbortSignal): Promise { const profileCount = Array.isArray(result.profiles) ? result.profiles.length : 0; if (profileCount === 0 && emptyProfileOutcome === "cancelled") { + timing.finish("cancelled"); send({ type: "cancelled" }); return; } if (profileCount === 0 && emptyProfileOutcome === "expired") { throw new Error("The GitHub device code expired"); } + if (profileCount < 1) + throw new Error("GitHub Copilot authentication did not create a credential profile"); + persisted?.(); + authenticated(); + timing.finish("success"); send({ type: "complete", profileCount, @@ -225,6 +400,9 @@ async function main(signal: AbortSignal): Promise { } if (require.main === module) { + const timing = new GitHubCopilotLoginTiming((event) => send({ ...event })); + timing.mark("worker-ready"); + const stopObserving = observeGitHubDeviceCodeRequests(timing); const cancellation = new AbortController(); const cancel = () => cancellation.abort(new Error("GitHub Copilot sign-in was cancelled")); const onMessage = (message: unknown) => { @@ -237,21 +415,24 @@ if (require.main === module) { }; process.on("message", onMessage); process.once("disconnect", cancel); - void main(cancellation.signal) + void main(cancellation.signal, timing) .catch((error) => { if ( cancellation.signal.aborted && (error === cancellation.signal.reason || (error instanceof Error && error.name === "AbortError")) - ) + ) { + timing.finish("cancelled"); send({ type: "cancelled" }); - else { + } else { + timing.finish("error"); process.stderr.write(`[github-copilot-auth] ${safeErrorMessage(error)}\n`); send({ type: "failure", message: safeErrorMessage(error) }); process.exitCode = 1; } }) .finally(() => { + stopObserving(); process.off("message", onMessage); process.off("disconnect", cancel); if (process.connected) process.disconnect?.(); diff --git a/desktop/src/github-copilot-auth.ts b/desktop/src/github-copilot-auth.ts index fde0388..0437cc0 100644 --- a/desktop/src/github-copilot-auth.ts +++ b/desktop/src/github-copilot-auth.ts @@ -2,8 +2,13 @@ import { spawn, type ChildProcess } from "node:child_process"; import * as fs from "node:fs"; import * as path from "node:path"; import { randomUUID } from "node:crypto"; +import { performance } from "node:perf_hooks"; import { CREATE_NO_WINDOW } from "./constants"; -import { resolveGitHubCopilotConfigRuntimePath } from "./github-copilot-auth-worker"; +import { + resolveGitHubCopilotConfigRuntimePath, + parseGitHubCopilotWorkerTiming, + type GitHubCopilotWorkerTiming, +} from "./github-copilot-auth-worker"; const MESSAGE_PREFIX = "MICROCLAW_COPILOT_AUTH:"; const GITHUB_DEVICE_URL = "https://github.com/login/device"; @@ -55,6 +60,7 @@ export type GitHubCopilotAuthEvent = | { sessionId: string; status: "error"; message: string }; type WorkerMessage = + | GitHubCopilotWorkerTiming | { type: "device-code"; verificationUrl: string; @@ -69,6 +75,8 @@ type WorkerMessage = interface ActiveLogin { sessionId: string; + startedAt: number; + workerReady: boolean; child: ChildProcess; timeout: ReturnType; terminal: boolean; @@ -125,6 +133,7 @@ export function parseGitHubCopilotWorkerLine(line: string): WorkerMessage | unde } const value = payload as Record; + if (value.type === "timing") return parseGitHubCopilotWorkerTiming(value); if (value.type === "device-code") { if (value.verificationUrl !== GITHUB_DEVICE_URL) { throw new Error("GitHub Copilot returned an unexpected verification URL"); @@ -506,8 +515,43 @@ export class GitHubCopilotAuthManager { constructor( private readonly emit: (event: GitHubCopilotAuthEvent) => void, private readonly openExternal: (url: string) => Promise, + private readonly logTiming: (record: Record) => void = () => {}, ) {} + private recordTiming( + active: ActiveLogin, + timing: { + phase: string; + status: string; + elapsedMs?: number; + durationMs?: number; + attempt?: number; + httpStatus?: number; + }, + source: "main" | "worker" = "main", + ): void { + const totalElapsedMs = Math.max(0, Math.round(performance.now() - active.startedAt)); + const record: Record = { + sessionId: active.sessionId, + source, + phase: timing.phase, + status: timing.status, + elapsedMs: timing.elapsedMs ?? totalElapsedMs, + totalElapsedMs, + }; + if (active.child.pid !== undefined) record.workerPid = active.child.pid; + for (const key of ["durationMs", "attempt", "httpStatus"] as const) { + if (timing[key] !== undefined) record[key] = timing[key]; + } + if (timing.phase === "login-total" && timing.status !== "started") + record.durationMs = totalElapsedMs; + try { + this.logTiming(record); + } catch { + /* Logging must not interrupt login. */ + } + } + getLoginSession(): { sessionId: string; cancelling: boolean; @@ -533,6 +577,7 @@ export class GitHubCopilotAuthManager { throw new Error("GitHub Copilot sign-in is still finishing cancellation"); return this.active.sessionId; } + const startedAt = performance.now(); const authRuntimePath = path.join( runtime.openClawPackageDir, "dist", @@ -568,6 +613,8 @@ export class GitHubCopilotAuthManager { }); const active: ActiveLogin = { sessionId, + startedAt, + workerReady: false, child, terminal: false, stdoutBuffer: "", @@ -576,11 +623,14 @@ export class GitHubCopilotAuthManager { cancellationRequested: false, closed, timeout: setTimeout(() => { + this.recordTiming(active, { phase: "login-timeout", status: "error" }); this.fail(active, "GitHub Copilot sign-in timed out"); }, AUTH_TIMEOUT_MS), }; active.timeout.unref?.(); this.active = active; + this.recordTiming(active, { phase: "login-total", status: "started" }); + this.recordTiming(active, { phase: "worker-startup", status: "started" }); child.stdout?.on("data", (chunk: Buffer) => this.handleOutput(active, chunk)); child.stderr?.on("data", (chunk: Buffer) => { @@ -597,6 +647,7 @@ export class GitHubCopilotAuthManager { false, ); } + this.recordTiming(active, { phase: "worker-exit", status: active.outcome ?? "error" }); resolveClosed(); }); return sessionId; @@ -619,6 +670,7 @@ export class GitHubCopilotAuthManager { private requestCancellation(active: ActiveLogin): void { if (active.cancellationRequested) return; active.cancellationRequested = true; + this.recordTiming(active, { phase: "cancellation-requested", status: "started" }); clearTimeout(active.timeout); // Let the SDK unwind credential persistence and release its locks. Hiding a // renderer panel never calls this; explicit cancellation does not kill it. @@ -654,6 +706,18 @@ export class GitHubCopilotAuthManager { private handleMessage(active: ActiveLogin, message: WorkerMessage): void { if (this.active !== active || active.terminal) return; + if (message.type === "timing") { + if (message.phase === "worker-ready" && !active.workerReady) { + active.workerReady = true; + this.recordTiming(active, { + phase: "worker-startup", + status: "success", + durationMs: Math.max(0, Math.round(performance.now() - active.startedAt)), + }); + } + this.recordTiming(active, message, "worker"); + return; + } if (message.type === "device-code") { active.codeExpiresAt = Date.now() + message.expiresInMs; active.code = { @@ -664,6 +728,7 @@ export class GitHubCopilotAuthManager { expiresInMs: message.expiresInMs, }; this.emit(active.code); + this.recordTiming(active, { phase: "device-code-delivered", status: "success" }); return; } if (message.type === "open-url") { @@ -684,6 +749,7 @@ export class GitHubCopilotAuthManager { } active.terminal = true; active.outcome = "cancelled"; + this.recordTiming(active, { phase: "login-total", status: "cancelled" }); clearTimeout(active.timeout); this.active = null; invalidateGitHubCopilotAuthStatusCache(); @@ -697,6 +763,7 @@ export class GitHubCopilotAuthManager { active.terminal = true; active.outcome = "success"; + this.recordTiming(active, { phase: "login-total", status: "success" }); clearTimeout(active.timeout); this.active = null; invalidateGitHubCopilotAuthStatusCache(); @@ -716,6 +783,7 @@ export class GitHubCopilotAuthManager { } active.terminal = true; active.outcome = "error"; + this.recordTiming(active, { phase: "login-total", status: "error" }); active.failureMessage = message; clearTimeout(active.timeout); this.active = null; diff --git a/desktop/src/github-copilot-login-timing.test.ts b/desktop/src/github-copilot-login-timing.test.ts new file mode 100644 index 0000000..07c97bd --- /dev/null +++ b/desktop/src/github-copilot-login-timing.test.ts @@ -0,0 +1,240 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { channel } from "node:diagnostics_channel"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import * as ts from "typescript"; +import { + GitHubCopilotLoginTiming, + observeGitHubDeviceCodeRequests, + type GitHubCopilotWorkerTiming, +} from "./github-copilot-auth-worker"; +import { + GitHubCopilotAuthManager, + parseGitHubCopilotWorkerLine, + type GitHubCopilotAuthEvent, +} from "./github-copilot-auth"; + +const roots: string[] = []; +afterEach(() => { + vi.restoreAllMocks(); + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +describe("Copilot login timing", () => { + it("measures monotonic phase durations and closes incomplete phases on failure", () => { + let now = 100; + const records: GitHubCopilotWorkerTiming[] = []; + const timing = new GitHubCopilotLoginTiming( + (record) => records.push(record), + () => now, + ); + const imported = timing.begin("sdk-import"); + now = 112; + imported(); + imported(); + timing.begin("config-read"); + now = 118; + timing.finish("error"); + expect( + records.map(({ phase, status, durationMs, elapsedMs }) => [ + phase, + status, + durationMs, + elapsedMs, + ]), + ).toEqual([ + ["sdk-import", "started", undefined, 0], + ["sdk-import", "success", 12, 12], + ["config-read", "started", undefined, 12], + ["config-read", "error", 6, 18], + ]); + const broken = new GitHubCopilotLoginTiming(() => { + throw new Error("Disk unavailable"); + }); + expect(() => broken.begin("sdk-import")()).not.toThrow(); + }); + + it("observes only device-code transport, without logging request or response content", () => { + const records: GitHubCopilotWorkerTiming[] = []; + const timing = new GitHubCopilotLoginTiming((record) => records.push(record)); + const unsubscribe = observeGitHubDeviceCodeRequests(timing); + const request = { + origin: "https://github.com", + path: "/login/device/code", + body: "private-device-secret", + }; + try { + channel("undici:request:create").publish({ + request: { ...request, origin: "https://other.invalid" }, + }); + channel("undici:request:create").publish({ + request: { ...request, path: "/login/oauth/access_token" }, + }); + expect(records).toEqual([]); + channel("undici:request:create").publish({ request }); + channel("undici:request:headers").publish({ + request, + response: { statusCode: 200, headers: "private-header" }, + }); + channel("undici:request:trailers").publish({ request, trailers: "private-trailer" }); + channel("undici:request:error").publish({ + request, + error: new Error("private-network-error"), + }); + expect(records).toHaveLength(2); + expect(records[1]).toMatchObject({ + phase: "device-code-http", + status: "success", + attempt: 1, + httpStatus: 200, + }); + expect(JSON.stringify(records)).not.toMatch(/private|github\.com|access_token/); + } finally { + unsubscribe(); + } + channel("undici:request:create").publish({ request }); + expect(records).toHaveLength(2); + }); + + it("drops malformed telemetry and strips arbitrary fields before persistence", () => { + const frame = { + type: "timing", + phase: "sdk-import", + status: "success", + elapsedMs: 42, + durationMs: 40, + }; + expect( + parseGitHubCopilotWorkerLine( + `MICROCLAW_COPILOT_AUTH:${JSON.stringify({ ...frame, token: "private", userCode: "ABCD-1234" })}`, + ), + ).toEqual(frame); + for (const patch of [ + { phase: "private" }, + { status: "private" }, + { status: { toString: 1 } }, + { elapsedMs: -1 }, + { durationMs: "private" }, + ]) { + expect( + parseGitHubCopilotWorkerLine( + `MICROCLAW_COPILOT_AUTH:${JSON.stringify({ ...frame, ...patch })}`, + ), + ).toBeUndefined(); + } + }); + + it.each(["success", "failure", "cancelled"] as const)( + "records a standalone worker's %s lifecycle without exposing its code or token", + async (outcome) => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "microclaw-copilot-timing-")); + roots.push(root); + const runtimeRoot = path.join(root, "runtime"); + const sdk = path.join(runtimeRoot, "dist", "plugin-sdk"); + fs.mkdirSync(sdk, { recursive: true }); + fs.writeFileSync(path.join(runtimeRoot, "package.json"), '{"type":"module"}'); + fs.writeFileSync( + path.join(sdk, "runtime-config-snapshot.js"), + "export const getRuntimeConfig = () => ({});", + ); + fs.writeFileSync( + path.join(sdk, "provider-catalog-runtime.js"), + "export const resolvePluginProviders = () => [{ id: 'github-copilot' }];", + ); + fs.writeFileSync( + path.join(sdk, "provider-auth-login-flow-runtime.js"), + ` + import { channel } from 'node:diagnostics_channel'; + export async function runModelsAuthLoginFlow(options) { + const request = { origin: 'https://github.com', path: '/login/device/code', body: 'private-token' }; + channel('undici:request:create').publish({ request }); + channel('undici:request:headers').publish({ request, response: { statusCode: 200 } }); + channel('undici:request:trailers').publish({ request }); + await options.prompter.note('URL: https://github.com/login/device\\nCode: ABCD-1234\\nCode expires in 15 minutes.'); + if (${JSON.stringify(outcome)} === 'cancelled') { + await new Promise((resolve, reject) => { + if (options.signal.aborted) reject(options.signal.reason); + else options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true }); + }); + } + await options.beforePersistentEffect?.(); + if (${JSON.stringify(outcome)} === 'failure') throw new Error('Synthetic persistence failure'); + return { profiles: [{ profileId: 'private-profile' }], defaultModel: 'github-copilot/test' }; + } + `, + ); + const workerPath = path.join(root, "worker.cjs"); + fs.writeFileSync( + workerPath, + ts.transpileModule( + fs.readFileSync(path.join(__dirname, "github-copilot-auth-worker.ts"), "utf8"), + { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022, + esModuleInterop: true, + }, + }, + ).outputText, + ); + const events: GitHubCopilotAuthEvent[] = []; + const records: Array> = []; + const manager = new GitHubCopilotAuthManager( + (event) => events.push(event), + async () => {}, + (record) => { + records.push(record); + if (record.phase === "config-read") throw new Error("Synthetic diagnostic write failure"); + }, + ); + const sessionId = manager.start({ + nodePath: process.execPath, + entryPath: path.join(runtimeRoot, "openclaw.mjs"), + workerPath, + openClawPackageDir: runtimeRoot, + stateDir: path.join(root, "state"), + compileCacheDir: path.join(root, "cache"), + }); + try { + await vi.waitFor(() => expect(events.some((event) => event.status === "code")).toBe(true)); + if (outcome === "cancelled") await manager.cancel(sessionId); + await vi.waitFor(() => + expect(records.some((record) => record.phase === "worker-exit")).toBe(true), + ); + expect(events.at(-1)?.status).toBe(outcome === "failure" ? "error" : outcome); + for (const phase of [ + "worker-startup", + "sdk-import", + "config-read", + "provider-prepare", + "device-code-http", + "device-code-delivered", + ]) { + expect( + records.some((record) => record.phase === phase && record.status === "success"), + ).toBe(true); + } + expect( + records.some( + (record) => + record.phase === "login-total" && + record.status === (outcome === "failure" ? "error" : outcome), + ), + ).toBe(true); + const save = records.filter((record) => record.phase === "credential-save-and-refresh"); + if (outcome === "cancelled") expect(save).toEqual([]); + else expect(save.at(-1)?.status).toBe(outcome === "failure" ? "error" : "success"); + expect( + records.every( + (record) => record.sessionId === sessionId && Number.isFinite(record.totalElapsedMs), + ), + ).toBe(true); + expect(JSON.stringify(records)).not.toMatch(/ABCD-1234|private-token|private-profile/); + } finally { + await manager.stop(); + } + }, + ); +}); diff --git a/desktop/src/main.ts b/desktop/src/main.ts index 1829c91..3a9fc1e 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -1647,6 +1647,8 @@ const githubCopilotAuthManager = new GitHubCopilotAuthManager( if (event.status === "success") void refreshGatewayGitHubCopilotAuthStatus(); }, (url) => shell.openExternal(url), + (timing) => + electronLifecycleDiagnostics.log("github-copilot-login-timing", timing, { durable: false }), ); // --------------------------------------------------------------------------- diff --git a/docs/reference/github-copilot-login-timing.md b/docs/reference/github-copilot-login-timing.md new file mode 100644 index 0000000..73b3583 --- /dev/null +++ b/docs/reference/github-copilot-login-timing.md @@ -0,0 +1,28 @@ +# GitHub Copilot 登录分阶段计时 + +桌面主进程将 `github-copilot-login-timing` 事件写入用户数据目录下的 `diagnostics/electron-lifecycle.jsonl`(Windows 默认是 `%APPDATA%/microclaw/diagnostics/electron-lifecycle.jsonl`)。使用 `sessionId` 关联一次登录,`workerPid` 可以与 OpenClaw 日志中的进程 ID 对照。 + +| 阶段 | 记录的范围 | +| --- | --- | +| `worker-startup` | 主进程收到登录请求至独立登录进程开始执行 | +| `sdk-import` | 并行导入认证、提供商目录和配置 SDK | +| `config-read` | 读取配置并准备内存中的 Copilot 配置 | +| `provider-prepare` | 加载并确认 Copilot 提供商 | +| `auth-flow` | 调用 SDK 登录流程至返回,包含下面的请求、授权和保存阶段 | +| `device-code-http` | GitHub 设备码 HTTP 请求创建至响应体接收结束;附请求序号和 HTTP 状态码 | +| `device-code-ready` | SDK 将设备码交给登录进程 | +| `device-code-delivered` | 主进程将设备码事件发送给界面;不代表界面完成绘制 | +| `authorization-and-model-check` | 设备码就绪至 SDK 开始持久化;包含用户授权、轮询和提供商模型检查 | +| `credential-save-and-refresh` | SDK 的 `beforePersistentEffect` 回调至登录流程返回;包含凭据保存和认证刷新 | +| `login-total` | 后端登录请求至成功、失败或取消;不含页面先前的状态检查和登录后的模型列表加载 | +| `worker-exit` | 登录进程退出,便于确认取消清理是否结束 | + +`status` 为 `started`、`success`、`error` 或 `cancelled`。`durationMs` 是阶段耗时,`elapsedMs` 是事件在所属进程中的相对时间,`totalElapsedMs` 是主进程从登录请求开始计算的累计时间。计时使用单调时钟。嵌套阶段与总耗时不可相加;用户授权时间也不应算作程序启动耗时。 + +设备码 HTTP 计时通过 Node 的 Undici 诊断通道观测,不替换请求实现、不读取请求体或响应体。DNS 和 SDK 的请求前检查可能发生在该 HTTP 阶段之前。SDK 未发出相应事件时,日志不会伪造阶段边界。 + +日志仅接受固定阶段名称、状态和数值,丢弃额外字段。不记录一次性授权码、设备码、令牌、请求头、响应内容或凭据配置。诊断失败不会阻断登录。未完成的阶段在失败或取消时记录相应状态,主进程也记录总超时和取消请求。 + +快速定位:若 `worker-startup` 慢,检查进程启动;若 `sdk-import` 或 `provider-prepare` 慢,检查本地加载;若 `device-code-http` 慢,检查 GitHub 请求。若 `auth-flow` 开始后很久都没有 HTTP 开始事件,则还需检查 SDK 的请求前准备。`device-code-delivered.totalElapsedMs` 可用于比较后端收到请求到出码的耗时。 + +修改后需重新构建并运行更新后的桌面程序和独立认证 worker;旧安装包不会自动获得这些计时事件。