Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Mac app: open outside pages in the default browser

Pixel (kwant bot)4c0d11f76e21
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 018c7681..342bc381 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -102,6 +102,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
approvals, so failed tasks waiting on a fix showed 0 next to a full column. It now counts the column's
cards, and a task whose check waits for your OK sits in Needs you. A failure's panel says the summary,
what to fix and whether AutoFix retries once each, instead of up to three times.
+- **Mac app: sign-in pages open in your browser.** Outside pages, such as a Google or Cloudflare
+ sign-in, no longer take over the kwant window with no way back. The window only shows kwant; every
+ other link opens in your default browser. Connecting an MCP server, a Composio app or Claude still
+ finishes: the app notices the sign-in by itself, and the browser tab says to go back to kwant.
- **Mission Control: racing Redo requests make one copy, and restore refuses unknown forced paths.**
Two Redo requests on the same flag at the same moment, without an `Idempotency-Key`, could each make
a copy; now the flag is claimed in the same step as the copy, so one wins and the rest get 409. A
diff --git a/apps/mac/README.md b/apps/mac/README.md
index cbc13b06..b7ab2735 100644
--- a/apps/mac/README.md
+++ b/apps/mac/README.md
@@ -8,6 +8,11 @@ A Tauri v2 shell around kwant. The app links the `kwnt` crate and runs the same
app opens a window on it and starts nothing. If something else holds the port, it uses a free one.
- **PATH:** apps opened from Finder get a bare PATH, so the app merges the login shell's PATH with
`/opt/homebrew/bin`, `/usr/local/bin` and `~/.local/bin` to find `claude`, `codex` and `grok`.
+- **Links:** the window only shows kwant (its loopback page and the bundled loading page). Any other
+ web or mail address, including sign-in pages and `target=_blank` links, opens in the default
+ browser; the app never opens a second window. Other schemes (`file:`, app links) are ignored.
+ The page sees `window.__KWANT_APP__ = 'mac'`, so sign-ins say to finish in the browser and watch
+ the server for the result. See `src/links.rs`.
- **Menu bar:** Open kwant, a status line (approvals waiting), Quit. Closing the window keeps kwant
running; Quit stops it.
- **Updates:** 15 seconds after start and then every 6 hours the app reads
diff --git a/apps/mac/src/links.rs b/apps/mac/src/links.rs
new file mode 100644
index 00000000..b651ecc5
--- /dev/null
+++ b/apps/mac/src/links.rs
@@ -0,0 +1,133 @@
+//! Where a link goes. The window only ever shows kwant: its own page on loopback and the bundled
+//! "Starting kwant…" page. Any other web or mail address opens in the person's default browser,
+//! so a sign-in page can never take over the window with no way back.
+
+use tauri::Url;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Link {
+ /// Load it in the kwant window.
+ Stay,
+ /// Cancel it here and open it in the default browser.
+ Browser,
+ /// Cancel it and open nothing (file:, javascript:, other apps' schemes).
+ Drop,
+}
+
+/// kwant's own page on this port, or the bundled loading page.
+fn is_kwant(url: &Url, port: u16) -> bool {
+ match url.scheme() {
+ // the bundled loading page (tauri://localhost on macOS, http://tauri.localhost elsewhere)
+ "tauri" => url.host_str() == Some("localhost"),
+ "http" if url.host_str() == Some("tauri.localhost") => true,
+ "http" => matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]")) && url.port() == Some(port),
+ _ => false,
+ }
+}
+
+/// kwant's server itself, which the browser can reach too (not the bundled page).
+fn is_kwant_server(url: &Url, port: u16) -> bool {
+ url.scheme() == "http" && url.host_str() != Some("tauri.localhost") && is_kwant(url, port)
+}
+
+/// A top-level navigation in the kwant window.
+pub fn navigation(url: &Url, port: u16) -> Link {
+ if is_kwant(url, port) {
+ return Link::Stay;
+ }
+ match url.scheme() {
+ // blank pages and in-page content kwant makes itself (downloads, previews)
+ "about" | "blob" | "data" => Link::Stay,
+ "http" | "https" | "mailto" => Link::Browser,
+ _ => Link::Drop,
+ }
+}
+
+/// A window.open() or target=_blank request. The app never opens a second window: real
+/// addresses, kwant's own included, go to the browser; a blank popup is refused, so the page's
+/// window.open() gets null and falls back to a navigation that `navigation` sends to the browser.
+pub fn new_window(url: &Url, port: u16) -> Link {
+ match navigation(url, port) {
+ Link::Stay if is_kwant_server(url, port) => Link::Browser,
+ Link::Stay => Link::Drop,
+ other => other,
+ }
+}
+
+/// Opens the address in the default browser (macOS `open`). Only http(s) and mailto reach here.
+pub fn open_in_browser(url: &Url) {
+ let url = url.as_str().to_string();
+ std::thread::spawn(
+ move || match std::process::Command::new("/usr/bin/open").arg(&url).status() {
+ Ok(s) if s.success() => {}
+ Ok(s) => tracing::warn!(status = %s, "the browser didn't open the link"),
+ Err(e) => tracing::warn!(error = %e, "couldn't open the link in the browser"),
+ },
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const PORT: u16 = 8799;
+
+ fn nav(s: &str) -> Link {
+ navigation(&s.parse().unwrap(), PORT)
+ }
+
+ fn popup(s: &str) -> Link {
+ new_window(&s.parse().unwrap(), PORT)
+ }
+
+ #[test]
+ fn kwant_pages_stay() {
+ assert_eq!(nav("http://127.0.0.1:8799/"), Link::Stay);
+ assert_eq!(nav("http://127.0.0.1:8799/api/mcp/oauth/callback?code=x"), Link::Stay);
+ assert_eq!(nav("http://localhost:8799/#/missions"), Link::Stay);
+ assert_eq!(nav("http://[::1]:8799/"), Link::Stay);
+ assert_eq!(nav("tauri://localhost/index.html"), Link::Stay);
+ assert_eq!(nav("http://tauri.localhost/index.html"), Link::Stay);
+ assert_eq!(nav("about:blank"), Link::Stay);
+ assert_eq!(nav("blob:http://127.0.0.1:8799/5f0c"), Link::Stay);
+ }
+
+ #[test]
+ fn outside_pages_go_to_the_browser() {
+ assert_eq!(
+ nav("https://accounts.google.com/o/oauth2/auth?client_id=x"),
+ Link::Browser
+ );
+ assert_eq!(nav("https://dash.cloudflare.com/oauth2/auth"), Link::Browser);
+ assert_eq!(nav("http://example.com/"), Link::Browser);
+ assert_eq!(nav("mailto:[email protected]"), Link::Browser);
+ // another port on this machine is another program, not kwant
+ assert_eq!(nav("http://127.0.0.1:3000/"), Link::Browser);
+ assert_eq!(nav("http://127.0.0.1/"), Link::Browser);
+ // https on kwant's port isn't how the app reaches kwant
+ assert_eq!(nav("https://127.0.0.1:8799/"), Link::Browser);
+ // a look-alike host
+ assert_eq!(nav("http://127.0.0.1.evil.example:8799/"), Link::Browser);
+ assert_eq!(nav("https://localhost.example/"), Link::Browser);
+ }
+
+ #[test]
+ fn other_schemes_are_dropped() {
+ assert_eq!(nav("file:///etc/passwd"), Link::Drop);
+ assert_eq!(nav("javascript:alert(1)"), Link::Drop);
+ assert_eq!(nav("vscode://file/x"), Link::Drop);
+ assert_eq!(nav("tauri://evil/index.html"), Link::Drop);
+ }
+
+ #[test]
+ fn new_windows_never_open_in_the_app() {
+ assert_eq!(popup("https://accounts.google.com/"), Link::Browser);
+ assert_eq!(popup("http://127.0.0.1:8799/sandbox/team-1"), Link::Browser);
+ assert_eq!(popup("mailto:[email protected]"), Link::Browser);
+ // the blank popup a sign-in pre-opens is refused, so the page falls back to a navigation
+ assert_eq!(popup("about:blank"), Link::Drop);
+ assert_eq!(popup("tauri://localhost/index.html"), Link::Drop);
+ assert_eq!(popup("http://tauri.localhost/index.html"), Link::Drop);
+ assert_eq!(popup("file:///tmp/x"), Link::Drop);
+ }
+}
diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rs
index c2089280..32fa77b6 100644
--- a/apps/mac/src/main.rs
+++ b/apps/mac/src/main.rs
@@ -1,6 +1,7 @@
//! kwant for Mac: the kwant server in this process, its UI in a window, and a menu-bar icon.
//! Closing the window keeps kwant running; Quit in the menu stops it.
+mod links;
mod startup;
mod update;
@@ -10,6 +11,7 @@ use std::time::Duration;
use tauri::{
menu::{Menu, MenuItem, PredefinedMenuItem},
tray::TrayIconBuilder,
+ webview::NewWindowResponse,
Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent,
};
@@ -150,10 +152,31 @@ fn open_window(handle: &tauri::AppHandle) {
let _ = window.set_focus();
return;
}
+ let port = handle.state::<Target>().port;
let window = match WebviewWindowBuilder::new(handle, MAIN, WebviewUrl::App("index.html".into()))
.title("kwant")
.inner_size(1280.0, 820.0)
.min_inner_size(900.0, 600.0)
+ // Tells kwant's page it runs in the app, so sign-ins say "finish in your browser"
+ .initialization_script("window.__KWANT_APP__ = 'mac';")
+ // The window only shows kwant; every other page opens in the default browser
+ .on_navigation(move |url| match links::navigation(url, port) {
+ links::Link::Stay => true,
+ links::Link::Browser => {
+ links::open_in_browser(url);
+ false
+ }
+ links::Link::Drop => {
+ tracing::info!(scheme = url.scheme(), "blocked a link the app doesn't open");
+ false
+ }
+ })
+ .on_new_window(move |url, _| {
+ if links::new_window(&url, port) == links::Link::Browser {
+ links::open_in_browser(&url);
+ }
+ NewWindowResponse::Deny
+ })
.build()
{
Ok(w) => w,
@@ -162,7 +185,6 @@ fn open_window(handle: &tauri::AppHandle) {
return;
}
};
- let port = handle.state::<Target>().port;
std::thread::spawn(move || {
if startup::wait_for_health(port, Duration::from_secs(120)).is_none() {
tracing::error!(port, "kwant didn't answer within 2 minutes");
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 01a75c7b..c7cca016 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -114,7 +114,9 @@ earlier attempt. Registrations are reused per server, callback URL and authoriza
Where the provider redirects the popup. kwnt exchanges the code and stores the tokens, then
returns a small HTML page that runs
`window.opener.postMessage({type: "kwnt-mcp-oauth", server_id, ok, error?}, location.origin)`
-and closes itself (or goes to `/` when it has no opener). `server_id` is null when the `state`
+and closes itself. With no opener it goes to `/` only when the app marked the tab before leaving
+it (sessionStorage `kwnt-mcp-oauth-return`); otherwise, as in the browser tab the Mac app opens,
+it stays and says to go back, and the app sees the sign-in in `GET /api/mcp/servers`. `server_id` is null when the `state`
is unknown, expired or already used. `error` is a short readable reason.
### `DELETE /api/mcp/servers/:id/oauth`
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 6f48c174..53538b60 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -100,6 +100,7 @@ import { personFetch } from './auth';
import { teamChannelOf, teamOfChannel } from './teamChannel';
import { PromptContext, suggestedPrompts } from './suggestedPrompts';
import { isNotificationOpen, showDeviceNotification } from './push';
+import { inMacApp, leaveForSignIn, mcpSignIn, pollUntil, signInChanged } from './externalLinks';
// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),
// so both load right after start-up and opening them never waits.
@@ -1710,8 +1711,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
};
// Same flow as the servers screen: the window opens inside the click, the address comes after.
+ // In the Mac app the sign-in opens in the default browser and the server is watched instead.
const handleSuggestionSignIn = async (serverId: string): Promise<string | void> => {
- const popup = window.open('', 'kwnt-mcp-oauth', 'popup,width=520,height=720');
+ const macApp = inMacApp();
+ const popup = macApp ? null : window.open('', 'kwnt-mcp-oauth', 'popup,width=520,height=720');
+ const before = macApp ? await mcpSignIn(serverId).catch(() => undefined) : undefined;
let url: string;
try {
const res = await fetch(`/api/mcp/servers/${encodeURIComponent(serverId)}/oauth/start`, {
@@ -1728,19 +1732,26 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
return `Couldn't start the sign-in: ${errText(err)}`;
}
if (!popup || popup.closed) {
- window.location.assign(url);
- return;
+ leaveForSignIn(url);
+ if (!macApp) return;
+ const finished = await new Promise<boolean>((resolve) => {
+ pollUntil(async () => signInChanged(before, await mcpSignIn(serverId)), () => resolve(true), {
+ onTimeout: () => resolve(false),
+ });
+ });
+ if (!finished) return 'The sign-in didn’t finish in your browser. Try again.';
+ } else {
+ popup.location.href = url;
+ popup.focus();
+ await new Promise<void>((resolve) => {
+ const t = window.setInterval(() => {
+ if (popup.closed) {
+ window.clearInterval(t);
+ resolve();
+ }
+ }, 500);
+ });
}
- popup.location.href = url;
- popup.focus();
- await new Promise<void>((resolve) => {
- const t = window.setInterval(() => {
- if (popup.closed) {
- window.clearInterval(t);
- resolve();
- }
- }, 500);
- });
try {
const test = await suggestionsApi.testServer(serverId);
if (test.ok) {
diff --git a/frontend/src/components/ClaudeSignIn.tsx b/frontend/src/components/ClaudeSignIn.tsx
index 96c4e3b8..7aad9f9d 100644
--- a/frontend/src/components/ClaudeSignIn.tsx
+++ b/frontend/src/components/ClaudeSignIn.tsx
@@ -3,6 +3,7 @@ import { AlertTriangle, ExternalLink, Loader2, LogIn, LogOut, RotateCcw } from '
import { ClaudeLoginError, ClaudeLoginSession, claudeLoginApi, isClaudeSignInUrl, isLoginActive, loginFailure } from '../claudeLogin';
import type { EngineInfo } from '../engines';
import { playSfx } from '../audio/chiptune';
+import { inMacApp } from '../externalLinks';
const POLL_MS = 2000;
@@ -15,6 +16,8 @@ const link = 'inline-flex items-center gap-1 font-medium text-sky-300 underline
/** A blank tab opened while the click still counts as a user gesture, so popup blockers allow it.
* `noopener` would make window.open return null, so the opener is cut by hand before navigating. */
function openBlankTab(): Window | null {
+ // The Mac app opens no second window; the link below opens in the default browser.
+ if (inMacApp()) return null;
try {
const tab = window.open('about:blank', '_blank');
if (tab) tab.opener = null;
@@ -37,6 +40,8 @@ export const ClaudeSignIn: React.FC<{ onSignedIn: () => void; focusRequest?: num
/** The new tab didn't open: show the link instead. */
const [blocked, setBlocked] = useState(false);
const tab = useRef<Window | null>(null);
+ /** Mac app: the link goes to the default browser once it arrives (no blank tab to fill). */
+ const toBrowser = useRef(false);
const startRef = useRef<HTMLButtonElement>(null);
const codeRef = useRef<HTMLInputElement>(null);
const retryRef = useRef<HTMLButtonElement>(null);
@@ -52,7 +57,13 @@ export const ClaudeSignIn: React.FC<{ onSignedIn: () => void; focusRequest?: num
/** Sends the blank tab to the link once there is one; once only. */
const showLink = useCallback((s: ClaudeLoginSession) => {
const t = tab.current;
- if (!t || !isClaudeSignInUrl(s.url)) return;
+ if (!isClaudeSignInUrl(s.url)) return;
+ if (!t && toBrowser.current) {
+ toBrowser.current = false;
+ window.location.assign(s.url);
+ return;
+ }
+ if (!t) return;
tab.current = null;
if (t.closed) setBlocked(true);
else t.location.replace(s.url);
@@ -62,7 +73,8 @@ export const ClaudeSignIn: React.FC<{ onSignedIn: () => void; focusRequest?: num
playSfx('click');
const t = openBlankTab();
tab.current = t;
- setBlocked(!t);
+ toBrowser.current = inMacApp();
+ setBlocked(!t && !toBrowser.current);
setBusy('start');
setError(null);
setCode('');
@@ -221,7 +233,7 @@ export const ClaudeSignIn: React.FC<{ onSignedIn: () => void; focusRequest?: num
</p>
{url && (
<p className="text-[11px] text-zinc-400">
- {blocked ? 'Your browser didn’t open a new tab. ' : 'Closed the tab? '}
+ {blocked ? 'Your browser didn’t open a new tab. ' : inMacApp() ? 'Opened claude.ai in your browser. ' : 'Closed the tab? '}
<a href={url} target="_blank" rel="noopener noreferrer" className={link} onClick={() => setBlocked(false)}>
{blocked ? 'Open claude.ai to sign in' : 'Open claude.ai again'} <ExternalLink size={10} aria-hidden="true" />
</a>
diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsx
index 8fbd1baf..4dbdcade 100644
--- a/frontend/src/components/ConnectionsView.tsx
+++ b/frontend/src/components/ConnectionsView.tsx
@@ -20,6 +20,7 @@ import {
storedLabel,
usedByText,
} from '../connections';
+import { inMacApp } from '../externalLinks';
const TONES: Record<Tone, string> = {
amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',
@@ -175,13 +176,15 @@ export const ComposioAppSearch: React.FC<{
const connect = async (app: ComposioApp) => {
// open the tab now, while the click still counts as the person's, then point it at Composio
- const tab = typeof window !== 'undefined' ? window.open('', '_blank') : null;
+ // The Mac app opens no second window: its links go to the default browser.
+ const tab = typeof window !== 'undefined' && !inMacApp() ? window.open('', '_blank') : null;
if (tab) tab.opener = null;
setConnecting(app.slug);
setError(null);
try {
const { redirect_url } = await api.connect(app.slug);
if (tab) tab.location.href = redirect_url;
+ else if (inMacApp()) window.location.assign(redirect_url);
else window.open(redirect_url, '_blank', 'noopener,noreferrer');
setOpened(app.name);
} catch (err) {
@@ -223,7 +226,7 @@ export const ComposioAppSearch: React.FC<{
{error && <p className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 text-xs text-rose-300">{error}</p>}
{opened && (
<p className="text-xs text-emerald-200">
- Opened {opened}’s sign-in on Composio in a new tab. Its tools reach your bots through the Composio server once you finish there.
+ Opened {opened}’s sign-in on Composio in {inMacApp() ? 'your browser' : 'a new tab'}. Its tools reach your bots through the Composio server once you finish there.
</p>
)}
{apps && apps.length === 0 && <p className="text-xs text-zinc-400">No Composio apps match.</p>}
diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsx
index 5bd5e283..b0bea20c 100644
--- a/frontend/src/components/McpServersModal.tsx
+++ b/frontend/src/components/McpServersModal.tsx
@@ -57,6 +57,7 @@ import {
readOAuthMessage,
isBlankRequired,
} from '../mcp';
+import { inMacApp, leaveForSignIn, pollUntil, signInChanged } from '../externalLinks';
interface McpServersModalProps {
isOpen: boolean;
@@ -381,6 +382,9 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
const [confirmDisconnect, setConfirmDisconnect] = useState<string | null>(null);
const popupRef = useRef<Window | null>(null);
const popupWatch = useRef<number | null>(null);
+ /** Mac app: stops watching the server for a sign-in finished in the browser. */
+ const signInWatch = useRef<(() => void) | null>(null);
+ const macApp = inMacApp();
const refresh = useCallback(async (): Promise<McpServer[] | null> => {
try {
@@ -401,6 +405,8 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
if (popupWatch.current !== null) window.clearInterval(popupWatch.current);
popupWatch.current = null;
popupRef.current = null;
+ signInWatch.current?.();
+ signInWatch.current = null;
}, []);
const setStatus = useCallback((id: string, status: StoredStatus | null) => {
@@ -500,8 +506,10 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
const connect = async (server: McpServer) => {
playSfx('click');
setOauthErrors(({ [server.id]: _, ...rest }) => rest);
+ const before = server.oauth;
// Open the window inside the click so popup blockers allow it; the address comes after the fetch.
- const popup = window.open('', 'kwnt-mcp-oauth', 'popup,width=520,height=720');
+ // The Mac app never opens a second window: its sign-ins go to the default browser.
+ const popup = macApp ? null : window.open('', 'kwnt-mcp-oauth', 'popup,width=520,height=720');
if (popup) {
try {
popup.document.title = 'Signing in…';
@@ -532,7 +540,27 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
}
if (!popup || popup.closed) {
// Blocked anyway: sign in in this tab. kwnt brings you back to the app afterwards.
- window.location.assign(url);
+ leaveForSignIn(url);
+ if (macApp) {
+ // The browser can't report back to the app: watch the server for the new sign-in.
+ stopWatchingPopup();
+ const stopWaiting = () => {
+ signInWatch.current = null;
+ setConnecting((c) => (c === server.id ? null : c));
+ };
+ signInWatch.current = pollUntil(
+ async () => {
+ const list = await refresh();
+ return signInChanged(before, list?.find((s) => s.id === server.id)?.oauth);
+ },
+ () => {
+ stopWaiting();
+ setOauthErrors(({ [server.id]: _, ...rest }) => rest);
+ runTest(server.id);
+ },
+ { onTimeout: stopWaiting },
+ );
+ }
return;
}
popup.location.href = url;
@@ -749,7 +777,9 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
<KeyRound size={13} className="flex-shrink-0 mt-px text-amber-400" />
<span>
{isConnecting
- ? 'Waiting for you to approve access in the sign-in window…'
+ ? macApp
+ ? 'Finish signing in in your browser. This updates by itself when you’re done.'
+ : 'Waiting for you to approve access in the sign-in window…'
: 'This server asks you to sign in and approve access.'}
</span>
</div>
@@ -762,11 +792,11 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
<button
type="button"
onClick={() => connect(server)}
- disabled={isConnecting}
+ disabled={isConnecting && !macApp}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[11px] font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-60"
>
- {isConnecting ? <Loader2 size={12} className="animate-spin" /> : <KeyRound size={12} />}
- {isConnecting ? 'Waiting…' : oauthError ? 'Retry' : 'Connect'}
+ {isConnecting && !macApp ? <Loader2 size={12} className="animate-spin" /> : <KeyRound size={12} />}
+ {isConnecting ? (macApp ? 'Open the sign-in again' : 'Waiting…') : oauthError ? 'Retry' : 'Connect'}
</button>
</div>
)}
diff --git a/frontend/src/components/McpSuggestionCard.tsx b/frontend/src/components/McpSuggestionCard.tsx
index fb8dab7a..59ec7711 100644
--- a/frontend/src/components/McpSuggestionCard.tsx
+++ b/frontend/src/components/McpSuggestionCard.tsx
@@ -2,6 +2,7 @@ import React, { useState } from 'react';
import { AlertTriangle, CheckCircle2, ExternalLink, Globe, KeyRound, Loader2, MinusCircle, Monitor, Plug } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { Suggestion, SuggestionMeta, failureText, inputKey, inputLabel, installPayload, runsLine, suggestionView } from '../mcpSuggestions';
+import { inMacApp } from '../externalLinks';
export interface McpSuggestionCardProps {
meta: SuggestionMeta;
@@ -245,7 +246,7 @@ export const McpSuggestionCard: React.FC<McpSuggestionCardProps> = ({
className="inline-flex items-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3.5 rounded-xl text-sm font-medium bg-amber-500 text-zinc-950 hover:bg-amber-400 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-400"
>
{busy === 'signin' && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
- {busy === 'signin' ? 'Waiting for sign-in…' : signInError ? 'Try signing in again' : 'Sign in'}
+ {busy === 'signin' ? (inMacApp() ? 'Finish signing in in your browser…' : 'Waiting for sign-in…') : signInError ? 'Try signing in again' : 'Sign in'}
</button>
{signInError && (
<span role="alert" className="text-rose-300 break-words">
diff --git a/frontend/src/externalLinks.ts b/frontend/src/externalLinks.ts
new file mode 100644
index 00000000..25844331
--- /dev/null
+++ b/frontend/src/externalLinks.ts
@@ -0,0 +1,85 @@
+/**
+ * Sign-ins that leave kwant. In a browser they open in a popup or, when it is blocked, in this
+ * tab, and kwnt's callback page brings the tab back. The Mac app's window only ever shows kwant
+ * (apps/mac/src/links.rs): every outside page opens in the default browser, with no opener and
+ * no way to come back by itself, so the app watches the server for the finished sign-in instead.
+ */
+
+/** sessionStorage mark for kwnt's callback page: this tab left kwant to sign in, bring it back.
+ * Same key as RETURN_KEY in src/server/mcp_oauth.rs. */
+export const OAUTH_RETURN_KEY = 'kwnt-mcp-oauth-return';
+
+type AppWindow = { __KWANT_APP__?: unknown };
+
+/** True inside the kwant Mac app, which marks its window with `__KWANT_APP__ = 'mac'`. */
+export const inMacApp = (w: unknown = typeof window !== 'undefined' ? window : undefined): boolean =>
+ !!w && (w as AppWindow).__KWANT_APP__ === 'mac';
+
+/**
+ * Goes to a sign-in page from this tab. In a browser the tab leaves kwant and the callback page
+ * returns it; in the Mac app the navigation is turned into the default browser and the window
+ * stays where it is.
+ */
+export function leaveForSignIn(url: string, w: Window = window): void {
+ if (!inMacApp(w)) {
+ try {
+ w.sessionStorage.setItem(OAUTH_RETURN_KEY, '1');
+ } catch {
+ // storage off: the callback page then says to go back instead of going back itself
+ }
+ }
+ w.location.assign(url);
+}
+
+/** What a server's sign-in looked like before Connect, to tell a new sign-in from an old one. */
+export type SignInMark = { connected: boolean; expires_at: string | null } | undefined;
+
+/** A sign-in finished since `before`: newly connected, or connected again with a new expiry. */
+export const signInChanged = (before: SignInMark, now: SignInMark): boolean =>
+ !!now?.connected && (!before?.connected || before.expires_at !== now.expires_at);
+
+/**
+ * Calls `check` every `everyMs` until it says done (then `onDone`) or `forMs` passes (then
+ * `onTimeout`). A failed check just waits for the next one. Returns a stop function.
+ */
+export function pollUntil(
+ check: () => Promise<boolean>,
+ onDone: () => void,
+ { everyMs = 2000, forMs = 10 * 60_000, onTimeout }: { everyMs?: number; forMs?: number; onTimeout?: () => void } = {},
+): () => void {
+ let stopped = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const until = Date.now() + forMs;
+ const tick = async () => {
+ if (stopped) return;
+ let done = false;
+ try {
+ done = await check();
+ } catch {
+ done = false;
+ }
+ if (stopped) return;
+ if (done) {
+ stopped = true;
+ onDone();
+ } else if (Date.now() >= until) {
+ stopped = true;
+ onTimeout?.();
+ } else {
+ timer = setTimeout(tick, everyMs);
+ }
+ };
+ timer = setTimeout(tick, everyMs);
+ return () => {
+ stopped = true;
+ if (timer !== null) clearTimeout(timer);
+ };
+}
+
+/** The sign-in state of one MCP server, from GET /api/mcp/servers. */
+export async function mcpSignIn(serverId: string, fetcher: typeof fetch = fetch): Promise<SignInMark> {
+ const res = await fetcher('/api/mcp/servers');
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const list = (await res.json()) as Array<{ id: string; oauth?: { connected: boolean; expires_at: string | null } }>;
+ return list.find((s) => s.id === serverId)?.oauth;
+}
diff --git a/frontend/tests/externalLinks.test.mjs b/frontend/tests/externalLinks.test.mjs
new file mode 100644
index 00000000..c680d342
--- /dev/null
+++ b/frontend/tests/externalLinks.test.mjs
@@ -0,0 +1,187 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ts from 'typescript';
+
+const source = await readFile(new URL('../src/externalLinks.ts', import.meta.url), 'utf8');
+const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2020 },
+});
+const { OAUTH_RETURN_KEY, inMacApp, leaveForSignIn, signInChanged, pollUntil, mcpSignIn } = await import(
+ `data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`
+);
+
+/** A window with sessionStorage and a location that records where it was sent. */
+const fakeWindow = (app) => {
+ const store = new Map();
+ const w = {
+ assigned: [],
+ sessionStorage: { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)) },
+ location: { assign: (url) => w.assigned.push(url) },
+ store,
+ };
+ if (app !== undefined) w.__KWANT_APP__ = app;
+ return w;
+};
+
+test('the callback page and the app agree on the return mark', async () => {
+ const rust = await readFile(new URL('../../src/server/mcp_oauth.rs', import.meta.url), 'utf8');
+ assert.match(rust, new RegExp(`RETURN_KEY: &str = "${OAUTH_RETURN_KEY}"`));
+});
+
+test('only the Mac app’s mark counts as the Mac app', () => {
+ assert.equal(inMacApp(fakeWindow('mac')), true);
+ assert.equal(inMacApp(fakeWindow()), false);
+ assert.equal(inMacApp(fakeWindow('windows')), false);
+ assert.equal(inMacApp(fakeWindow(true)), false);
+ assert.equal(inMacApp(undefined), false);
+});
+
+test('a browser tab that leaves to sign in is marked so the callback brings it back', () => {
+ const w = fakeWindow();
+ leaveForSignIn('https://mcp.example/authorize?x=1', w);
+ assert.deepEqual(w.assigned, ['https://mcp.example/authorize?x=1']);
+ assert.equal(w.store.get(OAUTH_RETURN_KEY), '1');
+});
+
+test('in the Mac app the window isn’t marked: the sign-in finishes in the browser, which has no opener', () => {
+ const w = fakeWindow('mac');
+ leaveForSignIn('https://dash.cloudflare.com/oauth2/auth', w);
+ // the app turns this navigation into the default browser; nothing should bring a browser tab to kwant
+ assert.deepEqual(w.assigned, ['https://dash.cloudflare.com/oauth2/auth']);
+ assert.equal(w.store.has(OAUTH_RETURN_KEY), false);
+});
+
+test('storage being off doesn’t stop the sign-in', () => {
+ const w = fakeWindow();
+ w.sessionStorage.setItem = () => {
+ throw new Error('SecurityError');
+ };
+ leaveForSignIn('https://x.example/', w);
+ assert.deepEqual(w.assigned, ['https://x.example/']);
+});
+
+test('a sign-in counts as finished only when it is new', () => {
+ const off = { connected: false, expires_at: null };
+ const on = { connected: true, expires_at: '2026-10-28T10:00:00Z' };
+ assert.equal(signInChanged(undefined, on), true);
+ assert.equal(signInChanged(off, on), true);
+ assert.equal(signInChanged(undefined, undefined), false);
+ assert.equal(signInChanged(off, off), false);
+ // signing in again over an existing sign-in: same expiry means nothing happened yet
+ assert.equal(signInChanged(on, on), false);
+ assert.equal(signInChanged(on, { connected: true, expires_at: '2026-10-28T11:00:00Z' }), true);
+ assert.equal(signInChanged(on, off), false);
+});
+
+test('pollUntil stops when the check says done, and survives failed checks', async () => {
+ let calls = 0;
+ const done = await new Promise((resolve) => {
+ pollUntil(
+ async () => {
+ calls += 1;
+ if (calls === 1) throw new Error('offline');
+ return calls >= 3;
+ },
+ () => resolve('done'),
+ { everyMs: 1, forMs: 5000, onTimeout: () => resolve('timeout') },
+ );
+ });
+ assert.equal(done, 'done');
+ assert.equal(calls, 3);
+});
+
+test('pollUntil gives up after its time and can be stopped', async () => {
+ const outcome = await new Promise((resolve) => {
+ pollUntil(async () => false, () => resolve('done'), { everyMs: 1, forMs: 10, onTimeout: () => resolve('timeout') });
+ });
+ assert.equal(outcome, 'timeout');
+
+ let calls = 0;
+ const stop = pollUntil(
+ async () => {
+ calls += 1;
+ return false;
+ },
+ () => assert.fail('stopped'),
+ { everyMs: 1 },
+ );
+ stop();
+ await new Promise((r) => setTimeout(r, 20));
+ assert.equal(calls, 0);
+});
+
+test('mcpSignIn reads one server’s sign-in from the list', async () => {
+ const list = [
+ { id: 'a', oauth: { connected: false, expires_at: null } },
+ { id: 'b', oauth: { connected: true, expires_at: 'x' } },
+ { id: 'c' },
+ ];
+ const fetcher = async (url) => {
+ assert.equal(url, '/api/mcp/servers');
+ return { ok: true, json: async () => list };
+ };
+ assert.deepEqual(await mcpSignIn('b', fetcher), { connected: true, expires_at: 'x' });
+ assert.equal(await mcpSignIn('c', fetcher), undefined);
+ assert.equal(await mcpSignIn('zzz', fetcher), undefined);
+ await assert.rejects(mcpSignIn('a', async () => ({ ok: false, status: 503 })), /503/);
+});
+
+/** Runs kwnt's callback-page script against a fake browser, the way the page would. */
+const runCallback = async (win) => {
+ const rust = await readFile(new URL('../../src/server/mcp_oauth.rs', import.meta.url), 'utf8');
+ // the script as format! writes it: {{ }} → { }, \" → ", {} slots → the message and the key
+ const tpl = rust.match(/<script>(\(function[\s\S]*?)<\/script>/)[1];
+ const js = tpl
+ .split('\\\n')
+ .map((l) => l.trim())
+ .join('')
+ .replace(/\{\}/, JSON.stringify({ type: 'kwnt-mcp-oauth', server_id: 's1', ok: true }))
+ .replace(/\{\}/, JSON.stringify(OAUTH_RETURN_KEY))
+ .replaceAll('{{', '{')
+ .replaceAll('}}', '}')
+ .replaceAll('\\"', '"');
+ new Function('window', 'location', 'sessionStorage', js)(win, win.location, win.sessionStorage);
+};
+
+const callbackWindow = ({ opener = null, marked = false } = {}) => {
+ const store = new Map(marked ? [[OAUTH_RETURN_KEY, '1']] : []);
+ const w = {
+ opener,
+ closed: false,
+ close: () => (w.closed = true),
+ replaced: [],
+ location: { origin: 'http://127.0.0.1:8799', replace: (u) => w.replaced.push(u) },
+ sessionStorage: {
+ getItem: (k) => store.get(k) ?? null,
+ removeItem: (k) => store.delete(k),
+ },
+ store,
+ };
+ return w;
+};
+
+test('callback page: a popup reports to its opener and closes', async () => {
+ const sent = [];
+ const w = callbackWindow({ opener: { postMessage: (m, o) => sent.push([m, o]) } });
+ await runCallback(w);
+ assert.equal(sent.length, 1);
+ assert.equal(sent[0][0].ok, true);
+ assert.equal(sent[0][1], 'http://127.0.0.1:8799');
+ assert.equal(w.closed, true);
+ assert.deepEqual(w.replaced, []);
+});
+
+test('callback page: a tab that left kwant goes back to it', async () => {
+ const w = callbackWindow({ marked: true });
+ await runCallback(w);
+ assert.deepEqual(w.replaced, ['/']);
+ assert.equal(w.store.has(OAUTH_RETURN_KEY), false);
+});
+
+test('callback page: the Mac app’s browser tab stays put and doesn’t load kwant', async () => {
+ const w = callbackWindow();
+ await runCallback(w);
+ assert.deepEqual(w.replaced, []);
+ assert.equal(w.closed, false);
+});
diff --git a/src/server/mcp_oauth.rs b/src/server/mcp_oauth.rs
index 73716db9..418799b3 100644
--- a/src/server/mcp_oauth.rs
+++ b/src/server/mcp_oauth.rs
@@ -250,8 +250,12 @@ fn script_json(v: &Value) -> String {
.replace('\u{2029}', "\\u2029")
}
-/// The page the sign-in popup lands on: tells the opener the outcome and closes, or goes to
-/// the app when there is no opener.
+/// The sessionStorage key the app sets before it leaves its own tab to sign in.
+pub const RETURN_KEY: &str = "kwnt-mcp-oauth-return";
+
+/// The page the sign-in popup lands on: tells the opener the outcome and closes. Without an
+/// opener it goes back to the app only when this tab left kwant to sign in ([`RETURN_KEY`]);
+/// a browser tab the Mac app opened just says to go back, and the app notices the sign-in itself.
pub fn callback_page(server_id: Option<&str>, result: Result<(), String>) -> Response {
let (ok, error) = match &result {
Ok(()) => (true, None),
@@ -261,17 +265,20 @@ pub fn callback_page(server_id: Option<&str>, result: Result<(), String>) -> Res
if let Some(e) = &error {
message["error"] = json!(e);
}
- let text = match &error {
- None => "Signed in. You can close this window.".to_string(),
- Some(e) => format!("Sign-in failed: {e}"),
+ let (text, next) = match &error {
+ None => ("Signed in.".to_string(), "You can close this tab and go back to kwant."),
+ Some(e) => (format!("Sign-in failed: {e}"), "Go back to kwant and try Connect again."),
};
let page = format!(
"<!doctype html><html><head><meta charset=\"utf-8\"><title>kwnt sign-in</title></head>\
- <body><p>{}</p><script>(function(){{var m={};\
- if(window.opener){{try{{window.opener.postMessage(m,location.origin)}}catch(e){{}}window.close()}}\
- else{{location.replace(\"/\")}}}})();</script></body></html>",
+ <body><p>{}</p><p>{}</p><script>(function(){{var m={},k={};\
+ if(window.opener){{try{{window.opener.postMessage(m,location.origin)}}catch(e){{}}window.close();return}}\
+ try{{if(sessionStorage.getItem(k)){{sessionStorage.removeItem(k);location.replace(\"/\")}}}}catch(e){{}}\
+ }})();</script></body></html>",
html_escape(&text),
- script_json(&message)
+ html_escape(next),
+ script_json(&message),
+ script_json(&json!(RETURN_KEY))
);
(
StatusCode::OK,
@@ -357,6 +364,19 @@ mod tests {
assert!(body.contains("postMessage(m,location.origin)"));
}
+ /// A browser tab the Mac app opened has no opener and no return mark: it stays on the page
+ /// and says to go back, instead of loading kwant in the browser.
+ #[test]
+ fn callback_page_without_opener_returns_only_when_marked() {
+ let resp = callback_page(Some("s1"), Ok(()));
+ let body = futures::executor::block_on(axum::body::to_bytes(resp.into_body(), 1 << 16)).unwrap();
+ let body = String::from_utf8(body.to_vec()).unwrap();
+ assert!(body.contains("You can close this tab and go back to kwant."), "{body}");
+ assert!(body.contains("k=\"kwnt-mcp-oauth-return\""), "{body}");
+ assert!(body.contains("if(sessionStorage.getItem(k)){sessionStorage.removeItem(k);location.replace(\"/\")}"), "{body}");
+ assert_eq!(body.matches("location.replace").count(), 1, "{body}");
+ }
+
#[test]
fn collects_request_hosts() {
let mut h = HeaderMap::new();