Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Keep connectors signed in across restarts: refresh each token once, and never wipe a sign-in by mistake (#202)
Eduardo Machadobeabdb625de4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9b31ea4..ad517c1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,7 +9,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht> - **Avisos no iPhone com o app fechado.** Aprovações, perguntas e respostas prontas chegam como notificação mesmo com o app fechado, e tocar abre a conversa.> - **Entrar na IA pelo navegador ou pelo iPhone, num Tucano em servidor.** O botão Entrar roda o login da própria IA no servidor e mostra a tela dele numa janela: a página pra abrir, o código pra digitar e um campo pra colar o código de volta. Sem SSH.>-> **Correções:** um agente com o GitHub em **Ler e escrever** volta a subir a branch e abrir a PR em vez de dizer que "a sessão é só leitura" (e, se algo pede aprovação ou está desligado, diz exatamente o quê); e o cartão **Computador** mostra o que vale pra cada escolha, sem misturar a confirmação de **Este computador** com o painel do Linux; e o QR code de Configurações › Celular › Seu iPhone traz o endereço do computador na rede de casa, que o iPhone alcança (antes, o nome .local fazia a conexão falhar).+> **Correções:** um agente com o GitHub em **Ler e escrever** volta a subir a branch e abrir a PR em vez de dizer que "a sessão é só leitura" (e, se algo pede aprovação ou está desligado, diz exatamente o quê); o cartão **Computador** mostra o que vale pra cada escolha, sem misturar a confirmação de **Este computador** com o painel do Linux; e um conector com login OAuth não pede pra autorizar de novo depois de uma atualização ou de horas aberto: duas renovações ao mesmo tempo não apagam mais o login, um servidor de login fora do ar só adia a reconexão, e **Autorizar no navegador** renova o login salvo antes de abrir o navegador.### Added@@ -22,6 +22,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht- **The iPhone connects to the computer's Tucano on a real home network.** The QR code in Settings › Phone › Your iPhone named the Mac by its Bonjour name (`name.local`), which the iPhone app couldn't reach on a real Wi-Fi: it waited and gave up with "Couldn't reach your Tucano", while the same QR code with the address connected. It now carries the computer's address on the home network, read each time a QR code is made, as on Windows and Linux.- **An agent with GitHub on "Ler e escrever" pushes and opens the PR instead of saying the session is read-only.** On Codex, the CLI's own text about its sandbox ("`sandbox_mode` is `read-only`... Network access is restricted", "Approval policy is never") reached the model, and it answered "Estou bloqueado porque esta sessão permite apenas leitura" for a push or a PR it had every grant for. That text is left out now (in `codex exec` and the app-server), and the note an agent with the app's tools gets says Codex's sandbox doesn't limit them, that git and other commands on its computer run with `bash`, and to say exactly what was refused or waits for approval, never "read-only". On every harness, an agent with a GitHub connector gets a **GitHub** section in its instructions, made from what it really has: the tools it publishes with (`create_branch`, `push_files`, `create_or_update_file`, `create_pull_request`, by the names it sees); on **Este computador**, that `git push` also runs with your own git credentials; on **Linux isolado**, that there are none there; what your autonomy level or rules make ask first or turn off; and, with read-only access, to ask for read and write with `pedir_acesso`. Before, an agent on this computer was told only "git push only when asked", with no word about the connector.- **The agent page's Computador card shows what each choice means, from the first look.** Clicking **Este computador** after **Linux isolado** showed the confirmation on top of the Linux panel (the Docker state, **Pastas do seu computador**, **Apagar computador**), with Linux still picked and already saved, and that mix read as this computer's full card, while the real one looked cut short. Now the confirmation shows alone, with **Este computador** picked, and **Cancelar** (or clicking the saved choice) goes back to it; once allowed, the card says the commands run on your computer as you, starting in its folder, and that it reaches your folders without lending them and needs no Docker.+- **OAuth connectors stay signed in across updates and long sessions.** A server that rotates refresh tokens takes each one once. When two requests found the access token expired together (two tool calls, or a call and the event stream), both renewed with the same refresh token: one got the new sign-in and saved it, the other got `invalid_grant`, and the MCP SDK deleted the saved sign-in, the new one included. The connector then asked for authorization at the next launch, which for an app left open is usually the update's. Now a renewal goes to the server once per refresh token and every request waiting on it gets the same answer, and a refusal deletes only the sign-in that was refused. A token endpoint that doesn't answer (a network error, a 5xx, a proxy's page) no longer reads as "Precisa autorizar": the connector says the renewal failed and tries again by itself. **Autorizar no navegador** first renews the saved sign-in, without the browser; before, it always registered the app again and threw the saved sign-in away. And a saved value the system's key won't open (the Keychain said no) is never deleted: the connector says so, with what to do, and doesn't retry; **Autorizar no navegador** then signs in again in its place.## [0.2.18] - 2026-11-07diff --git a/src/core/connectors.ts b/src/core/connectors.tsindex e3f35b8..fe2511c 100644--- a/src/core/connectors.ts+++ b/src/core/connectors.ts@@ -16,7 +16,7 @@ import { ownAppOf, type AppProvider, type CatalogEntry } from '../shared/connectimport type { Connector, ConnectorInput, ConnectorStatus, ConnectorTool } from '../shared/types'import type { Db } from './db'import { classify, legacyClassify } from './policy'-import type { Secrets } from './secrets'+import { unreadable, type Secrets } from './secrets'import { OpError, resolveOp, resolveOpRefs } from './onepassword'const CALL_TIMEOUT_MS = 120_000@@ -26,6 +26,8 @@ const MAX_STDIO_FAILURES = 3// A connection that dropped on its own (the server's process ended, the network went), or an attempt that// failed for a passing reason, is tried again after these waits; then it waits for a call or the button.const RECONNECT_DELAYS_MS = [2_000, 5_000, 15_000, 60_000, 300_000]+// How long a renewal's answer is kept for another request that renews with the same refresh token.+const RENEWAL_KEEP_MS = 60_000// The authorization page sent the browser back without a code: why, and what to do.export function notAuthorized(url: URL): string {@@ -121,6 +123,36 @@ interface Live {passing?: boolean // the last attempt failed for a reason that may go away by itself (network, timeout)}+// What happened to the renewals of one connection attempt.+interface Renewal {+ failed?: boolean // the token endpoint didn't answer, or answered with a server error: the sign-in may still be good+}++type Answer = { status: number; statusText: string; headers: [string, string][]; body: string }++// The OAuth error a token endpoint answered with (RFC 6749 §5.2), if it answered with one.+const oauthError = (a: Answer): string | undefined => {+ if (a.status < 400 || a.status >= 500 || a.status === 429) return undefined+ try {+ const error = (JSON.parse(a.body) as { error?: unknown }).error+ return typeof error === 'string' ? error : undefined+ } catch {+ return undefined+ }+}++// The saved sign-in couldn't be opened (the system's key): nothing was deleted, and it isn't the server's doing.+const unreadableMessage = (auth: Connector['auth']): string =>+ auth === 'oauth'+ ? L(+ 'Não consegui abrir o login salvo deste conector: o sistema não liberou a chave do Tucano. Nada foi apagado. Reinicie o Tucano e, se o sistema pedir acesso às chaves, permita; se não resolver, autorize de novo.',+ "I couldn't open this connector's saved sign-in: the system didn't release Tucano's key. Nothing was deleted. Restart Tucano and, if the system asks for access to the keys, allow it; if that doesn't help, authorize again."+ )+ : L(+ 'Não consegui abrir as credenciais salvas deste conector: o sistema não liberou a chave do Tucano. Nada foi apagado. Reinicie o Tucano e, se o sistema pedir acesso às chaves, permita; se não resolver, salve a credencial de novo.',+ "I couldn't open this connector's saved credentials: the system didn't release Tucano's key. Nothing was deleted. Restart Tucano and, if the system asks for access to the keys, allow it; if that doesn't help, save the credential again."+ )+// The call never ran, so it can go again on a new connection: the server forgot this session (it expired// while idle), or the client had no connection to send it on. Not "Connection closed": the SDK gives that to// every call already sent when the connection drops, which the server may have run (a write would go twice).@@ -180,6 +212,11 @@ export class ConnectorManager {private authUrls = new Map<string, string>() // a connector's last authorization pageprivate doneStates = new Set<string>() // finished already (the callback got there first): not an expired oneprivate closing = false // the app is quitting: nothing reconnects+ // Renewals under way or just done, by token endpoint and refresh token. A server that rotates refresh tokens+ // takes each one once: two requests renewing together would get one new sign-in and+ // one refusal, and the refusal made the SDK delete the sign-in the other had just saved.+ private renewals = new Map<string, Promise<Answer>>()+ private refused = new Set<string>() // refresh tokens a server refusedconstructor(private deps: ConnectorDeps) {}@@ -340,6 +377,7 @@ export class ConnectorManager {{ listChanged: { tools: { onChanged: () => void this.refreshTools(id).catch(() => {}) } } })let transport: Transport+ const renewal: Renewal = {}const own = c.kind === 'remote' && c.auth === 'oauth' ? this.appOf(c.url) : undefinedif (own && !(await this.deps.secrets.getJson<OwnApp>(appKey(own.provider)))) {const name = PROVIDER[own.provider]@@ -355,7 +393,8 @@ export class ConnectorManager {}const http: StreamableHTTPClientTransport = new StreamableHTTPClientTransport(new URL(c.url!), {requestInit: { headers },- authProvider: c.auth === 'oauth' ? this.oauthProvider(id, () => http, interactive, own) : undefined+ authProvider: c.auth === 'oauth' ? this.oauthProvider(id, () => http, interactive, own) : undefined,+ ...(c.auth === 'oauth' ? { fetch: this.renewingFetch(renewal) } : {})})transport = http} else {@@ -363,8 +402,8 @@ export class ConnectorManager {transport = new StdioClientTransport({ command: c.command!, args: c.args, env: { ...getDefaultEnvironment(), ...env }, stderr: 'ignore' })}} catch (e) {- // A 1Password secret that wasn't read: it needs you (unlock, install the CLI), so no retries.- this.setStatus(id, 'error', e instanceof OpError ? e.message : connectError(e))+ // A 1Password secret that wasn't read, or a saved one the system's key won't open: it needs you, so no retries.+ this.setStatus(id, 'error', unreadable(e) ? unreadableMessage(c.auth) : e instanceof OpError ? e.message : connectError(e))return}@@ -375,7 +414,17 @@ export class ConnectorManager {// Linear's), so its status says it, not its text.const refused =e instanceof UnauthorizedError || (e instanceof StreamableHTTPError && e.code === 401) || (e instanceof Error && /unauthorized|401/i.test(e.message))- if (refused && c.auth === 'token') {+ if (unreadable(e)) {+ // Not the server: the saved sign-in is there, encrypted, and stays. No retries, no browser.+ await client.close().catch(() => {})+ this.setStatus(id, c.auth === 'oauth' ? 'needs_auth' : 'error', unreadableMessage(c.auth))+ } else if (refused && renewal.failed && !interactive) {+ // The sign-in is still good: the server that renews it didn't answer. It tries again by itself.+ await client.close().catch(() => {})+ this.setStatus(id, 'error', L('Não consegui renovar o login agora: o servidor de autorização não respondeu. Tento de novo sozinho.', "I couldn't renew the sign-in just now: the authorization server didn't answer. I'll try again by myself."))+ this.live.get(id)!.passing = true+ this.reconnectLater(id)+ } else if (refused && c.auth === 'token') {// With a token there is no browser to go to: the server refused it, or there is none yet.await client.close().catch(() => {})this.setStatus(id, 'error', L('O servidor recusou o token. Salve um token válido neste conector.', 'The server refused the token. Save a valid token on this connector.'))@@ -513,12 +562,60 @@ export class ConnectorManager {// The authorization page's address comes back too: on a server there's no// browser to open it in, so the page the person is using opens it.+ // A sign-in that can still be renewed (the server was away, the attempt hit a passing error) comes back+ // without the browser: signing in again would register another app and throw the saved one away.async authorize(id: string): Promise<string | undefined> {this.authUrls.delete(id)+ if (this.live.get(id)?.client) return undefined+ if (await this.renewable(id)) {+ await this.connect(id).catch(() => {})+ if (this.live.get(id)?.client) return undefined+ }await this.connect(id, true).catch(() => {})return this.authUrls.get(id)}+ private async renewable(id: string): Promise<boolean> {+ const tokens = await this.deps.secrets.getJson<OAuthTokens>(key(id, 'oauth_tokens')).catch(() => undefined)+ return !!tokens?.refresh_token && !this.refused.has(tokens.refresh_token)+ }++ // The fetch an OAuth connection uses. A renewal (grant_type=refresh_token) goes to the server once per refresh+ // token: a request that renews with the same one meanwhile gets the same answer. It also notes a renewal the+ // server refused, and one that failed without saying the sign-in is bad (no answer, a server error).+ private renewingFetch(renewal: Renewal): typeof fetch {+ return async (input, init) => {+ const form = init?.body instanceof URLSearchParams ? init.body : undefined+ const refreshToken = form?.get('grant_type') === 'refresh_token' ? form.get('refresh_token') : null+ if (!refreshToken) return fetch(input, init)+ const k = `${input instanceof Request ? input.url : String(input)} ${refreshToken}`+ let answer = this.renewals.get(k)+ if (!answer) {+ answer = fetch(input, init).then(async (r) => ({ status: r.status, statusText: r.statusText, headers: [...r.headers], body: await r.text() }))+ this.renewals.set(k, answer)+ // A new sign-in or a refusal holds for whoever asks next; a failure is tried again.+ answer.then(+ (a) => (a.status < 300 || oauthError(a) !== undefined ? setTimeout(() => this.renewals.delete(k), RENEWAL_KEEP_MS).unref?.() : this.renewals.delete(k)),+ () => this.renewals.delete(k)+ )+ }+ let a: Answer+ try {+ a = await answer+ } catch (e) {+ renewal.failed = true+ throw e+ }+ if (a.status >= 300) {+ const error = oauthError(a)+ if (error === 'invalid_grant') this.refused.add(refreshToken)+ // No word on the sign-in itself: a proxy's page, a server error, too many requests.+ else if (error === undefined || error === 'server_error' || error === 'temporarily_unavailable') renewal.failed = true+ }+ return new Response(a.body, { status: a.status, statusText: a.statusText, headers: a.headers })+ }+ }+// On a server the authorization page sends the person's browser to the// callback on the server's own loopback, which it can't reach; the address// it was sent to carries the code, and the person pastes it here.@@ -549,6 +646,16 @@ export class ConnectorManager {private oauthProvider(id: string, transport: () => StreamableHTTPClientTransport, interactive: boolean, own?: CatalogEntry['app']): OAuthClientProvider {const { secrets } = this.depsconst redirectUrl = own ? this.redirectFor(own.provider) : this.deps.oauthCallbackUrl()+ // Signing in again (someone clicked Authorize) goes on past a saved value the system's key won't open:+ // the new sign-in takes its place. In the background it stops the attempt, and the value stays.+ const read = async <T>(k: string): Promise<T | undefined> => {+ try {+ return await secrets.getJson<T>(k)+ } catch (e) {+ if (interactive && unreadable(e)) return undefined+ throw e+ }+ }let state = ''return {get redirectUrl() {@@ -576,12 +683,12 @@ export class ConnectorManager {const app = await secrets.getJson<OwnApp>(appKey(own.provider))return app && { client_id: app.clientId, client_secret: app.clientSecret }}- const info = await secrets.getJson<OAuthClientInformationMixed & { redirect_uris?: string[] }>(key(id, 'oauth_client'))+ const info = await read<OAuthClientInformationMixed & { redirect_uris?: string[] }>(key(id, 'oauth_client'))const fits = (u: string): boolean => (interactive ? u === redirectUrl : sameLoopbackRedirect(u, redirectUrl))return info && (!info.redirect_uris || info.redirect_uris.some(fits)) ? info : undefined},saveClientInformation: (info) => (own ? undefined : secrets.setJson(key(id, 'oauth_client'), { ...info, redirect_uris: [redirectUrl] })),- tokens: () => secrets.getJson<OAuthTokens>(key(id, 'oauth_tokens')),+ tokens: () => read<OAuthTokens>(key(id, 'oauth_tokens')),saveTokens: (t) => secrets.setJson(key(id, 'oauth_tokens'), t),saveCodeVerifier: (v) => secrets.set(key(id, 'oauth_verifier'), v),codeVerifier: async () => (await secrets.get(key(id, 'oauth_verifier'))) ?? '',@@ -594,7 +701,11 @@ export class ConnectorManager {},invalidateCredentials: async (scope) => {if ((scope === 'all' || scope === 'client') && !own) await secrets.set(key(id, 'oauth_client'), undefined) // the app is the person's- if (scope === 'all' || scope === 'tokens') await secrets.set(key(id, 'oauth_tokens'), undefined)+ // Only a sign-in the server refused: one saved meanwhile (by a renewal that got there first) stays.+ if (scope === 'all' || scope === 'tokens') {+ const saved = await read<OAuthTokens>(key(id, 'oauth_tokens')).catch((e: unknown) => (unreadable(e) ? 'unreadable' : undefined))+ if (saved !== 'unreadable' && (scope === 'all' || !saved?.refresh_token || this.refused.has(saved.refresh_token))) await secrets.set(key(id, 'oauth_tokens'), undefined)+ }if (scope === 'all' || scope === 'verifier') await secrets.set(key(id, 'oauth_verifier'), undefined)}}diff --git a/src/core/secrets.ts b/src/core/secrets.tsindex 934cae3..1032582 100644--- a/src/core/secrets.ts+++ b/src/core/secrets.ts@@ -37,6 +37,23 @@ export function mainCipher(port: Electron.ParentPort): Cipher {return { encrypt: (s) => ask('encrypt', s), decrypt: (s) => ask('decrypt', s) }}+// A saved value that's there but can't be opened: the system's key changed or wasn't given (the Keychain+// said no). It stays as it was, encrypted: a later launch with the key back opens it again.+export class UnreadableSecret extends Error {+ constructor(+ readonly key: string,+ cause: unknown+ ) {+ super(cause instanceof Error ? cause.message : String(cause), { cause })+ this.name = 'UnreadableSecret'+ }+}++export const unreadable = (e: unknown): UnreadableSecret | undefined => {+ for (let x = e, i = 0; x && i < 5; x = (x as { cause?: unknown }).cause, i++) if (x instanceof UnreadableSecret) return x+ return undefined+}+export class Secrets {constructor(private db: Db,@@ -45,7 +62,13 @@ export class Secrets {async get(key: string): Promise<string | undefined> {const sealed = this.db.getSecret(key)- return sealed === undefined ? undefined : this.cipher.decrypt(sealed)+ if (sealed === undefined) return undefined+ try {+ return await this.cipher.decrypt(sealed)+ } catch (e) {+ console.error(`[secrets] couldn't open ${key}; it stays saved`) // the key only: never the value+ throw new UnreadableSecret(key, e)+ }}async getJson<T>(key: string): Promise<T | undefined> {diff --git a/src/main/index.ts b/src/main/index.tsindex f3f3c04..b5b868e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -296,7 +296,7 @@ function handleCore(child: UtilityProcess, msg: CoreRequest, workspace: Workspac} catch (e) {// Saved under another key (the system's changed, or the data came from another computer).console.error('[main] decrypt', e)- throw new Error(L('Não consegui abrir as credenciais salvas (a chave do sistema mudou). Conecte de novo.', "I couldn't open the saved credentials (the system's key changed). Connect again."))+ throw new Error(L('Não consegui abrir as credenciais salvas: a chave do sistema mudou ou não foi liberada. Elas continuam guardadas.', "I couldn't open the saved credentials: the system's key changed or wasn't released. They're still saved."))}}child.postMessage({ type: 'secret-result', id: msg.id, data })diff --git a/test/connectors-oauth.test.ts b/test/connectors-oauth.test.tsindex cd89ee6..b6976a3 100644--- a/test/connectors-oauth.test.ts+++ b/test/connectors-oauth.test.ts@@ -20,6 +20,12 @@ let registrations: numberlet refreshes: string[]let expireAccessToken: () => voidlet revokeRefreshTokens: () => void+// How the authorization server behaves: rotating refresh tokens (each works once, like Linear's and+// Notion's), a slow token endpoint (so two refreshes overlap), and a token endpoint that's down.+let rotate: boolean+let tokenDelayMs: number+let tokenDown: number // the next refreshes answer 503+let calls: numberconst body = async (req: import('node:http').IncomingMessage): Promise<string> => {const chunks: Buffer[] = []@@ -33,6 +39,10 @@ beforeEach(async () => {opened = []registrations = 0refreshes = []+ rotate = false+ tokenDelayMs = 0+ tokenDown = 0+ calls = 0let current = '' // only the newest access token works, as if the older one had expiredexpireAccessToken = () => {current = ''@@ -70,9 +80,19 @@ beforeEach(async () => {const refreshToken = form.get('refresh_token')if (refreshToken) {refreshes.push(`${clientId} (issued to ${owner.get(refreshToken) ?? 'nobody'})`)+ if (tokenDelayMs) await new Promise((r) => setTimeout(r, tokenDelayMs))+ if (tokenDown > 0) {+ tokenDown -= 1+ res.writeHead(502, { 'content-type': 'text/html' }).end('<html>Bad Gateway</html>')+ return+ }if (owner.get(refreshToken) !== clientId) return json(400, { error: 'invalid_grant' })- current = `at-${owner.size + 1}-${Date.now()}`- return json(200, { access_token: current, token_type: 'Bearer', expires_in: 3600, refresh_token: refreshToken })+ current = `at-${refreshes.length}-${Date.now()}`+ if (!rotate) return json(200, { access_token: current, token_type: 'Bearer', expires_in: 3600, refresh_token: refreshToken })+ owner.delete(refreshToken)+ const next = `rt-r${refreshes.length}`+ owner.set(next, clientId)+ return json(200, { access_token: current, token_type: 'Bearer', expires_in: 3600, refresh_token: next })}current = `at-${owner.size + 1}-${Date.now()}`const fresh = `rt-${owner.size + 1}`@@ -93,7 +113,11 @@ beforeEach(async () => {if (call.method === 'initialize') {return json(200, { jsonrpc: '2.0', id: call.id, result: { protocolVersion: call.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'fake', version: '1' } } })}- if (call.method === 'tools/list') return json(200, { jsonrpc: '2.0', id: call.id, result: { tools: [] } })+ if (call.method === 'tools/list') return json(200, { jsonrpc: '2.0', id: call.id, result: { tools: [{ name: 'search', inputSchema: { type: 'object' } }] } })+ if (call.method === 'tools/call') {+ calls += 1+ return json(200, { jsonrpc: '2.0', id: call.id, result: { content: [{ type: 'text', text: 'ok' }] } })+ }res.writeHead(202).end()})()})@@ -109,8 +133,17 @@ afterEach(async () => {})// One launch of the app, listening for the OAuth callback on its own port.-const launch = (callbackPort: number): ConnectorManager =>- new ConnectorManager({ db, secrets, emit: () => {}, openUrl: (u) => opened.push(u), oauthCallbackUrl: () => `http://127.0.0.1:${callbackPort}/oauth/callback` })+const launch = (callbackPort: number, withSecrets: Secrets = secrets): ConnectorManager =>+ new ConnectorManager({ db, secrets: withSecrets, emit: () => {}, openUrl: (u) => opened.push(u), oauthCallbackUrl: () => `http://127.0.0.1:${callbackPort}/oauth/callback` })++// A launch whose system key won't open what was saved (the Keychain said no, or the key changed).+const lockedOut = (): Secrets =>+ new Secrets(db, {+ encrypt: plainCipher.encrypt,+ decrypt: async () => {+ throw new Error("I couldn't open the saved credentials (the system's key changed).")+ }+ })describe('OAuth credentials across launches', () => {it('signs in once and refreshes on the next launch, when only the callback port changed', async () => {@@ -158,6 +191,102 @@ describe('OAuth credentials across launches', () => {})})+// Signs a new connector in on a first launch, then closes that launch with the access token gone stale.+const signedIn = async (): Promise<string> => {+ const first = launch(51001)+ const id = await first.add({ name: 'Linear', kind: 'remote', url: `${base}/mcp`, auth: 'oauth' })+ await first.connect(id)+ const state = new URL((await first.authorize(id))!).searchParams.get('state')!+ await first.finishOAuth(state, 'code-1')+ expect(first.get(id)!.status).toBe('connected')+ await first.closeAll()+ expireAccessToken()+ return id+}++describe('renewing the sign-in', () => {+ it('renews once when two calls find the access token expired together, and keeps the new refresh token', async () => {+ rotate = true+ tokenDelayMs = 50+ const id = await signedIn()+ const second = launch(51002)+ await second.connect(id)+ expect(second.get(id)!.status).toBe('connected')+ expireAccessToken() // it grows old again while the app is open+ const results = await Promise.allSettled([second.call(id, 'search', {}), second.call(id, 'search', {})])+ expect(results.map((r) => r.status)).toEqual(['fulfilled', 'fulfilled'])+ expect(await secrets.getJson(`connector:${id}:oauth_tokens`)).toMatchObject({ refresh_token: expect.stringMatching(/^rt-r/) })+ await second.closeAll()++ // And the next launch still renews on its own.+ expireAccessToken()+ const third = launch(51003)+ await third.connect(id)+ expect(third.get(id)!.status).toBe('connected')+ expect(opened).toHaveLength(1)+ await third.closeAll()+ })++ it("doesn't ask to sign in when the token endpoint is down at launch, and connects when it's back", async () => {+ const id = await signedIn()+ tokenDown = 1+ const second = launch(51002)+ await second.connect(id)+ expect(second.get(id)!.status).toBe('error')+ expect(second.get(id)!.error).toMatch(/renovar/)+ expect(await secrets.getJson(`connector:${id}:oauth_tokens`)).toMatchObject({ refresh_token: 'rt-1' })+ await second.connect(id) // the retry+ expect(second.get(id)!.status).toBe('connected')+ expect(opened).toHaveLength(1)+ await second.closeAll()+ })++ it('renews with the saved sign-in when Authorize is clicked, instead of signing in again', async () => {+ const id = await signedIn()+ tokenDown = 1+ const second = launch(51002)+ await second.connect(id) // fails for now+ expect(await second.authorize(id)).toBeUndefined()+ expect(second.get(id)!.status).toBe('connected')+ expect(opened).toHaveLength(1)+ expect(registrations).toBe(1)+ await second.closeAll()+ })+})++describe("a saved sign-in the system key won't open", () => {+ it('keeps it, says so once per connector without retrying, and works again once the key is back', async () => {+ const id = await signedIn()+ const before = db.getSecret(`connector:${id}:oauth_tokens`)+ const locked = launch(51002, lockedOut())+ await locked.connect(id)+ const c = locked.get(id)!+ expect(c.status).toBe('needs_auth')+ expect(c.error).toMatch(/Nada foi apagado|Nothing was deleted/)+ expect(db.getSecret(`connector:${id}:oauth_tokens`)).toBe(before)+ expect(db.getSecret(`connector:${id}:oauth_client`)).toBeDefined()+ expect(opened).toHaveLength(1)+ expect(refreshes).toEqual([]) // nothing went to the server+ await locked.closeAll()++ const back = launch(51003)+ await back.connect(id)+ expect(back.get(id)!.status).toBe('connected')+ expect(registrations).toBe(1)+ await back.closeAll()+ })++ it('signs in again when Authorize is clicked, in place of what it could not open', async () => {+ const id = await signedIn()+ const locked = launch(51002, lockedOut())+ await locked.connect(id)+ const page = await locked.authorize(id)+ expect(page).toBeTruthy()+ expect(opened).toHaveLength(2)+ await locked.closeAll()+ })+})+describe('the loopback redirect, port aside', () => {it('ignores only the port, and only on an http loopback address', () => {expect(sameLoopbackRedirect('http://127.0.0.1:51001/oauth/callback', 'http://127.0.0.1:52002/oauth/callback')).toBe(true)