Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(desktop): recover oauth on app activation (#748)

Gener666461583657
diff --git a/scripts/ci/native-oauth-desktop.test.ts b/scripts/ci/native-oauth-desktop.test.ts
index 268a51b17..7c25ef019 100644
--- a/scripts/ci/native-oauth-desktop.test.ts
+++ b/scripts/ci/native-oauth-desktop.test.ts
@@ -52,6 +52,8 @@ describe("desktop native OAuth security configuration", () => {
expect(runtime).toContain("channel.send(())")
expect(source).toContain("PageLoadEvent::Started")
expect(source).toContain("WindowEvent::Destroyed")
+ expect(source).toContain("tauri::WindowEvent::Focused(true)")
+ expect(source).not.toContain("tauri::RunEvent::Resumed")
expect(runtime).toContain('label == "main"')
expect(runtime).toContain("url.origin().ascii_serialization() == expected")
expect(runtime).toContain("url.username().is_empty()")
diff --git a/scripts/ci/native-oauth-mobile.test.ts b/scripts/ci/native-oauth-mobile.test.ts
index 13d06c61a..9de66dd89 100644
--- a/scripts/ci/native-oauth-mobile.test.ts
+++ b/scripts/ci/native-oauth-mobile.test.ts
@@ -142,6 +142,19 @@ describe("native OAuth mobile activation", () => {
)
})
+ it("maps one real mobile resume event to one OAuth re-drive", () => {
+ expect(rustEntry).toMatch(
+ /tauri::RunEvent::WindowEvent\s*\{\s*label,\s*event,\s*\.\./,
+ )
+ expect(rustEntry).toMatch(
+ /#\[cfg\(mobile\)\]\s*\{\s*matches!\(event, tauri::WindowEvent::Resumed\)/,
+ )
+ expect(rustEntry).not.toContain("tauri::RunEvent::Resumed")
+ expect(
+ rustEntry.match(/native_oauth_runtime::notify_listener\(app\)/g),
+ ).toHaveLength(1)
+ })
+
it("keeps generated Apple identity, entitlement, and fallback sources aligned", () => {
expect(ios).toEqual({
$schema: "./gen/schemas/ios-schema.json",
diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rs
index a5e0318d7..bd9b02350 100644
--- a/src/desktop/src-tauri/src/lib.rs
+++ b/src/desktop/src-tauri/src/lib.rs
@@ -204,10 +204,31 @@ fn run_app(builder: tauri::Builder<tauri::Wry>) {
.build(tauri::generate_context!())
.expect("error while building tauri application");
- app.run(|_app, _event| {
+ app.run(|app, event| {
+ if should_notify_native_oauth(&event) {
+ native_oauth_runtime::notify_listener(app);
+ }
#[cfg(target_os = "macos")]
- if let tauri::RunEvent::Reopen { .. } = _event {
- commands::show_main_window(_app);
+ if let tauri::RunEvent::Reopen { .. } = event {
+ commands::show_main_window(app);
}
});
}
+
+fn should_notify_native_oauth(event: &tauri::RunEvent) -> bool {
+ let tauri::RunEvent::WindowEvent { label, event, .. } = event else {
+ return false;
+ };
+ if label != "main" {
+ return false;
+ }
+
+ #[cfg(mobile)]
+ {
+ matches!(event, tauri::WindowEvent::Resumed)
+ }
+ #[cfg(desktop)]
+ {
+ matches!(event, tauri::WindowEvent::Focused(true))
+ }
+}
diff --git a/src/desktop/src-tauri/src/native_oauth_runtime.rs b/src/desktop/src-tauri/src/native_oauth_runtime.rs
index 6eb36fe86..23a883de3 100644
--- a/src/desktop/src-tauri/src/native_oauth_runtime.rs
+++ b/src/desktop/src-tauri/src/native_oauth_runtime.rs
@@ -121,6 +121,12 @@ pub fn retire_listener(app: &AppHandle) {
}
}
+pub fn notify_listener(app: &AppHandle) {
+ if let Some(state) = app.try_state::<NativeOauthState>() {
+ state.notify();
+ }
+}
+
fn intake(app: &AppHandle, url: &url::Url) {
let Some(state) = app.try_state::<NativeOauthState>() else {
return;
diff --git a/src/web/src/lib/native-oauth-client.test.ts b/src/web/src/lib/native-oauth-client.test.ts
index 43102c385..651a93ae5 100644
--- a/src/web/src/lib/native-oauth-client.test.ts
+++ b/src/web/src/lib/native-oauth-client.test.ts
@@ -7,6 +7,9 @@ function deferred<T>() {
const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })
return { promise, resolve, reject }
}
+const providers = ["github", "google", "apple"] as const
+const ambiguousExchangeCases = providers.flatMap(provider => [true, false].map(signedIn => ({ provider, signedIn })))
+
function setup() {
let snapshot: NativeOauthSnapshot | null = null
let pending: { attemptId: string; state: string; verifier: string; candidateId: string; code: string | null; status: string | null; wasDispatched: boolean }[] = []
@@ -87,7 +90,8 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
})
it("registers the listener before reading pending, opens only the registered start, and keeps proofs out of view state", async () => {
- const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")
+ const f = fixture(); f.hasSession.mockResolvedValue(true)
+ await f.controller.connect(); await f.controller.start("github", "/c/me")
expect(f.events.indexOf("listen")).toBeLessThan(f.events.indexOf("native_oauth_pending_exchange"))
expect(f.events.indexOf("attempt")).toBeLessThan(f.events.indexOf("native_oauth_open_start"))
expect(f.view().phase).toBe("waiting")
@@ -99,7 +103,8 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
expect(f.invoke).toHaveBeenCalledWith("native_oauth_finish", expect.anything())
})
it("rejects only a forged candidate and processes a later real code after durable retirement", async () => {
- const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me")
+ const f = fixture(); f.hasSession.mockResolvedValue(true)
+ await f.controller.connect(); await f.controller.start("google", "/c/me")
const normal = f.post.getMockImplementation()!
let exchanges = 0
f.post.mockImplementation(async endpoint => endpoint === "exchange" && ++exchanges === 1 ? { ok: false, data: { error: "invalid_handoff" } } : normal(endpoint))
@@ -109,7 +114,8 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
expect(f.invoke.mock.calls.filter(([name]) => name === "native_oauth_reject_candidate")).toHaveLength(1)
})
it("retires a known-invalid code even with status offline, then exchanges a genuine callback after reload", async () => {
- const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me")
+ const f = fixture(); f.hasSession.mockResolvedValue(true)
+ await f.controller.connect(); await f.controller.start("google", "/c/me")
const normal = f.post.getMockImplementation()!
let exchanges = 0
f.post.mockImplementation(async endpoint => {
@@ -163,8 +169,8 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
expect(f.view().message).toBeUndefined()
expect(f.snapshot()?.provider ?? null).toBe(replace ? "google" : null)
})
- it("does not trust a status URL that disagrees with the proof-protected server", async () => {
- const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")
+ it.each(providers)("does not trust a %s status URL that disagrees with the proof-protected server", async provider => {
+ const f = fixture(); await f.controller.connect(); await f.controller.start(provider, "/c/me")
f.queue(null, "access_denied"); f.wake()
await vi.waitFor(() => expect(f.view().message).toBe("invalid_callback"))
expect(f.snapshot()).not.toBeNull()
@@ -174,8 +180,8 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
await vi.waitFor(() => expect(f.view().message).toBe("denied"))
expect(f.snapshot()).toBeNull()
})
- it.each([true, false])("checks session after ambiguous exchange (session=%s) without replaying the code", async signedIn => {
- const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")
+ it.each(ambiguousExchangeCases)("checks $provider session after ambiguous exchange (session=$signedIn) without replaying the code", async ({ provider, signedIn }) => {
+ const f = fixture(); await f.controller.connect(); await f.controller.start(provider, "/c/me")
f.post.mockRejectedValue(new Error("network")); f.hasSession.mockResolvedValue(signedIn)
f.queue(); f.wake()
await vi.waitFor(() => expect(f.hasSession).toHaveBeenCalled())
@@ -184,8 +190,106 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
f.wake(); await new Promise(resolve => setTimeout(resolve, 0))
expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)
})
- it("recovers a cold candidate after listener setup, and never replays an already-dispatched persisted code", async () => {
+ it.each(providers)("reconciles a %s session when foregrounding after the callback was finished", async provider => {
+ const f = fixture(); f.hasSession.mockResolvedValue(true)
+ await f.controller.connect(); await f.controller.start(provider, "/c/me")
+ f.queue(); f.wake()
+ await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledOnce())
+ f.navigate.mockClear(); f.hasSession.mockClear()
+
+ f.wake()
+
+ await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledWith("/c/me"))
+ expect(f.hasSession).toHaveBeenCalledOnce()
+ expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)
+ })
+ it("ends resumed waiting with a retryable error when neither callback nor session exists", async () => {
+ const f = fixture(); f.hasSession.mockResolvedValue(false)
+ await f.controller.connect(); await f.controller.start("github", "/c/me")
+
+ f.wake()
+
+ await vi.waitFor(() => expect(f.view()).toMatchObject({ phase: "error", message: "retry_required" }))
+ expect(f.hasSession).toHaveBeenCalledOnce()
+ expect(f.navigate).not.toHaveBeenCalled()
+ })
+ it.each(providers)("ends resumed %s waiting with a retryable error when session refresh times out", async provider => {
+ const f = fixture(); f.hasSession.mockRejectedValue(new Error("timeout"))
+ await f.controller.connect(); await f.controller.start(provider, "/c/me")
+
+ f.wake()
+
+ await vi.waitFor(() => expect(f.view()).toMatchObject({ phase: "error", message: "retry_required" }))
+ expect(f.navigate).not.toHaveBeenCalled()
+ })
+ it("consumes a callback that arrives while resumed session reconciliation is in flight", async () => {
+ const f = fixture(); const session = deferred<boolean>()
+ f.hasSession.mockReturnValueOnce(session.promise).mockResolvedValue(true)
+ await f.controller.connect(); await f.controller.start("github", "/c/me")
+ f.wake()
+ await vi.waitFor(() => expect(f.hasSession).toHaveBeenCalledOnce())
+
+ f.queue(); f.wake(); session.resolve(false)
+
+ await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledWith("/c/me"))
+ expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)
+ })
+ it("requires a refreshed session before finishing a successful exchange", async () => {
+ const f = fixture(); f.hasSession.mockResolvedValue(false)
+ await f.controller.connect(); await f.controller.start("github", "/c/me")
+ f.queue(); f.wake()
+
+ await vi.waitFor(() => expect(f.view()).toMatchObject({ phase: "error", message: "retry_required" }))
+ expect(f.invoke.mock.calls.some(([name]) => name === "native_oauth_finish")).toBe(false)
+ expect(f.navigate).not.toHaveBeenCalled()
+ })
+ it.each(providers)("finishes %s on a later foreground when the session becomes visible after exchange", async provider => {
+ const f = fixture(); f.hasSession.mockResolvedValueOnce(false).mockResolvedValueOnce(true)
+ await f.controller.connect(); await f.controller.start(provider, "/c/me")
+ f.queue(); f.wake()
+ await vi.waitFor(() => expect(f.view()).toMatchObject({ phase: "error", message: "retry_required" }))
+
+ f.wake()
+
+ await vi.waitFor(() => expect(f.navigate).toHaveBeenCalledWith("/c/me"))
+ expect(f.hasSession).toHaveBeenCalledTimes(2)
+ expect(f.post.mock.calls.filter(([endpoint]) => endpoint === "exchange")).toHaveLength(1)
+ expect(f.invoke.mock.calls.filter(([name]) => name === "native_oauth_finish")).toHaveLength(1)
+ })
+ it("adopts a replacement attempt discovered during foreground reconciliation", async () => {
const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")
+ const replacement = {
+ ...f.snapshot()!,
+ attemptId: `attempt_${"9".repeat(24)}`,
+ provider: "google" as const,
+ }
+ const original = f.invoke.getMockImplementation()!
+ f.invoke.mockImplementation((command, args) => command === "native_oauth_snapshot" ? Promise.resolve(replacement) : original(command, args))
+
+ f.wake()
+
+ await vi.waitFor(() => expect(f.view()).toMatchObject({ phase: "waiting", attempt: replacement }))
+ expect(f.hasSession).not.toHaveBeenCalled()
+ expect(f.navigate).not.toHaveBeenCalled()
+ expect(f.invoke.mock.calls.some(([name]) => name === "native_oauth_finish")).toBe(false)
+ })
+ it.each(["cancel", "retry"] as const)("ignores resumed session reconciliation after %s", async action => {
+ const f = fixture(); const session = deferred<boolean>()
+ f.hasSession.mockReturnValue(session.promise)
+ await f.controller.connect(); await f.controller.start("github", "/c/me")
+ f.wake(); await vi.waitFor(() => expect(f.hasSession).toHaveBeenCalledOnce())
+
+ if (action === "cancel") await f.controller.cancel()
+ else await f.controller.start("google", "/c/me")
+ session.resolve(true); await new Promise(resolve => setTimeout(resolve, 0))
+
+ expect(f.navigate).not.toHaveBeenCalled()
+ expect(f.view().phase).toBe(action === "cancel" ? "idle" : "waiting")
+ expect(f.snapshot()?.provider ?? null).toBe(action === "cancel" ? null : "google")
+ })
+ it("recovers a cold candidate after listener setup, and never replays an already-dispatched persisted code", async () => {
+ const f = fixture(); f.hasSession.mockResolvedValue(false)
+ await f.controller.connect(); await f.controller.start("github", "/c/me")
f.queue("k".repeat(32), null, true); f.controller.dispose()
const restored = f.make(); controllers.push(restored); await restored.connect()
expect(f.hasSession).toHaveBeenCalledOnce()
@@ -285,8 +389,9 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
f.wake(); await vi.waitFor(() => expect(f.view().message).toBe("unavailable"))
expect(f.post.mock.calls.some(([endpoint]) => endpoint === "exchange")).toBe(false)
})
- it("recovers a candidate arriving during registration of the new document listener", async () => {
- const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me"); f.controller.dispose()
+ it.each(providers)("recovers a %s candidate arriving during registration of the new document listener", async provider => {
+ const f = fixture(); f.hasSession.mockResolvedValue(true)
+ await f.controller.connect(); await f.controller.start(provider, "/c/me"); f.controller.dispose()
f.listen.mockImplementation(async ready => { f.queue(); ready(); return f.stop })
const restored = f.make(); controllers.push(restored); await restored.connect()
expect(f.navigate).toHaveBeenCalledOnce()
diff --git a/src/web/src/lib/native-oauth-client.ts b/src/web/src/lib/native-oauth-client.ts
index 228868b2a..18efba7b3 100644
--- a/src/web/src/lib/native-oauth-client.ts
+++ b/src/web/src/lib/native-oauth-client.ts
@@ -34,6 +34,7 @@ export function createNativeOauthController(deps: NativeOauthDeps, changed: (vie
let stopListening: (() => void) | undefined
let processing = false
let wakeAgain = false
+ let reconcileAgain = false
let startQueue = Promise.resolve()
let expiry: ReturnType<typeof setTimeout> | undefined
const publish = (next: NativeOauthView) => {
@@ -61,17 +62,39 @@ export function createNativeOauthController(deps: NativeOauthDeps, changed: (vie
const confirmSession = async () => {
try { return await deps.hasSession() } catch { return false }
}
- const drain = async () => {
+ const drain = async (reconcileSession = false) => {
if (disposed || !connected) return
- if (processing) { wakeAgain = true; return }
+ if (processing) {
+ wakeAgain = true
+ reconcileAgain ||= reconcileSession
+ return
+ }
processing = true
const version = generation
+ let shouldReconcile = reconcileSession
try {
do {
+ shouldReconcile ||= reconcileAgain
+ reconcileAgain = false
wakeAgain = false
const candidate = exchangeSchema.nullable().parse(await deps.invoke("native_oauth_pending_exchange"))
if (!current(version)) return
- if (!candidate) return
+ if (!candidate) {
+ const attempt = view.attempt
+ if (!shouldReconcile || !attempt?.waiting) return
+ const snapshot = await readSnapshot()
+ if (!current(version)) return
+ if (snapshot && snapshot.attemptId !== attempt.attemptId) {
+ publish({ phase: snapshot.waiting ? "waiting" : "idle", attempt: snapshot })
+ return
+ }
+ const signedIn = await confirmSession()
+ if (!current(version)) return
+ if (signedIn) deps.navigate(attempt.redirectPath)
+ else publish({ phase: "error", message: "retry_required", attempt: snapshot })
+ return
+ }
+ shouldReconcile = false
const snapshot = await readSnapshot()
if (!current(version)) return
if (!snapshot || snapshot.attemptId !== candidate.attemptId) continue
@@ -95,6 +118,12 @@ export function createNativeOauthController(deps: NativeOauthDeps, changed: (vie
if (!current(version)) return
const success = z.object({ redirectPath: z.string().refine(isSafeRedirectPath) }).strict().safeParse(response.data)
if (response.ok && success.success) {
+ const signedIn = await confirmSession()
+ if (!current(version)) return
+ if (!signedIn) {
+ publish({ phase: "error", message: "retry_required", attempt: snapshot })
+ return
+ }
await finish(attemptId, candidateId)
if (current(version)) deps.navigate(success.data.redirectPath)
return
@@ -139,14 +168,19 @@ export function createNativeOauthController(deps: NativeOauthDeps, changed: (vie
if (current(version)) publish({ phase: "error", message: "unavailable", attempt: view.attempt })
} finally {
processing = false
- if (wakeAgain && !disposed) { wakeAgain = false; void drain() }
+ if (wakeAgain && !disposed) {
+ const reconcile = reconcileAgain
+ wakeAgain = false
+ reconcileAgain = false
+ void drain(reconcile)
+ }
}
}
return {
async connect() {
publish({ phase: "initializing", attempt: null })
try {
- const unsubscribe = await deps.listen(() => { void drain() })
+ const unsubscribe = await deps.listen(() => { void drain(true) })
if (disposed) { unsubscribe(); return }
stopListening = unsubscribe
const attempt = await readSnapshot()