From 539602b2d1a5136fc7a95ddd50bfafd71b4d7af9 Mon Sep 17 00:00:00 2001 From: olibaron Date: Mon, 23 Nov 2026 21:14:35 +0100 Subject: [PATCH 1/3] fix(ui-auth-aeven): a window-flow provider sign-in finishes in exactly one window (#773) The landing chose between closing and booting the app from window.opener. The sign-in starts at aeven.io/oauth/, whose Cross-Origin-Opener-Policy: same-origin clears the opener (and the window name) on the way back, so the popup booted the app while the page that opened it booted as well. A landing without its opener or the provider window's name now announces itself on a same-origin BroadcastChannel under the window flow and closes only when a page waiting on a provider window claims it; unclaimed, it goes on to the app. The waiting page boots on the announcement and keeps claiming for 30 s after its own session read. A refused close shows a signed-in note (zh/en/es) instead of a second shell. Redirect-flow landings go on at once, as before. Closes #773 Co-Authored-By: Claude Opus 5.5 --- ...2026-09-21-provider-sign-in-flow.i18n.yaml | 4 +- .../2026-09-21-provider-sign-in-flow.md | 2 +- .../2026-09-21-provider-sign-in-flow.zh.md | 2 +- packages/client/ui-auth-aeven/package.json | 1 + .../src/client/auth/services/oauth.ts | 102 ++++++++++++++++-- .../src/client/auth/views/Authenticate.tsx | 4 +- .../src/client/auth/views/OauthResult.tsx | 34 +++--- .../ui-auth-aeven/src/client/locales.ts | 6 ++ .../ui-auth-aeven/tests/oauth.client.spec.ts | 70 +++++++++++- packages/client/ui-auth-aeven/tsconfig.json | 3 + pnpm-lock.yaml | 3 + 11 files changed, 201 insertions(+), 30 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.i18n.yaml index 11b56f3665..7076fca959 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.md -2026-09-21-provider-sign-in-flow.md: 1f22d85ecc5029a6332ba7ae52a12a8145c97331 -2026-09-21-provider-sign-in-flow.zh.md: 8dbb8fe9194f14a993c8dc0d95816662bb9c4aa7 +2026-09-21-provider-sign-in-flow.md: ba8bc36c54bcb3e1798c5cbb2fa0650740da04e3 +2026-09-21-provider-sign-in-flow.zh.md: e21f656d1d1a792e1eacca4b579fa5cdafaa4d4e diff --git a/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.md b/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.md index 1f22d85ecc..ba8bc36c54 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.md +++ b/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.md @@ -22,7 +22,7 @@ Nothing in the page said which shape the deployment wanted, so the client could **Under `window`, the provider is reached from a window of its own and the page never moves.** `openProviderSignIn(url)` opens it under a fixed name, so a second provider button replaces the first window instead of stacking another behind it. -**The session is the handoff, not a message between documents.** The landing window is this application's own `/oauth-result`, so it exchanges the provider's answer itself — the same `checkOauthToken` and `getProfile` a redirected document runs — which establishes the session in the origin's cookies, shared by both windows. `OauthResult` then reports by closing: a landing in a window this application opened is where the sign-in finishes, not where the application belongs ([the boot gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.md) is what would otherwise boot a shell inside it, and the window that opened it is already waiting). The document that opened the window waits for that session with `awaitProviderSession()`, reading the profile until the API answers one, and then continues exactly as it does after the email form: read the profile, move off the authentication surface, and let the gate boot. +**The session is the handoff, not a message between documents.** The landing window is this application's own `/oauth-result`, so it exchanges the provider's answer itself — the same `checkOauthToken` and `getProfile` a redirected document runs — which establishes the session in the origin's cookies, shared by both windows. `OauthResult` then reports by closing: a landing in a window this application opened is where the sign-in finishes, not where the application belongs ([the boot gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.md) is what would otherwise boot a shell inside it, and the window that opened it is already waiting). The opener does not mark that window: the sign-in starts at `aeven.io/oauth/`, whose `Cross-Origin-Opener-Policy: same-origin` clears both `window.opener` and `window.name` on the way back, so a landing without either asks over the origin's `BroadcastChannel` whether a page is waiting on a provider window and closes only when one claims it; unclaimed, it goes on to the application itself, so exactly one window boots ([issue 773](https://github.com/Aeven-AI/Aeven/issues/773)). The waiting page keeps claiming for 30 s after its own read of the session, because the landing announces itself only after its profile read. A browser that refuses the close shows a signed-in note instead of a second shell. The document that opened the window waits for that session with `awaitProviderSession()`, reading the profile until the API answers one, and then continues exactly as it does after the email form: read the profile, move off the authentication surface, and let the gate boot. **A refusal is still shown where a refused sign-in is shown.** A landing that carries an error, or one whose exchange fails, leaves the apology on screen in the window that opened, exactly as `redirect` shows it; this document keeps waiting, and the reader closing that window leaves them on the sign-in screen with the button in their hands. diff --git a/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.zh.md b/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.zh.md index 8dbb8fe919..e21f656d1d 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.zh.md @@ -22,7 +22,7 @@ Status: implemented **在 `window` 下,提供方由独立窗口抵达,页面本身永不移动。** `openProviderSignIn(url)` 以固定名称打开该窗口,因此读者第二次按下提供方按钮时替换第一个窗口,而不是在其后叠出第二个。 -**交接靠的是会话,而不是文档之间的消息。** 落地窗口就是本应用自己的 `/oauth-result`,因此它自行交换提供方的回答——与跳转文档所运行的同一套 `checkOauthToken` 与 `getProfile`——从而在该 origin 的 cookie 中建立会话,两个窗口共享它。随后 `OauthResult` 以关闭窗口来报告:由本应用打开的窗口中的落地,是登录完成之处,而不是应用该存在之处(否则[启动 gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.zh.md) 会在其中启动一个外壳,而打开它的那个文档已经在等待了)。打开该窗口的文档用 `awaitProviderSession()` 等待该会话,反复读取 profile 直到 API 给出一个,随后完全按邮件表单之后的方式继续:读取 profile、离开认证界面,并让 gate 启动。 +**交接靠的是会话,而不是文档之间的消息。** 落地窗口就是本应用自己的 `/oauth-result`,因此它自行交换提供方的回答——与跳转文档所运行的同一套 `checkOauthToken` 与 `getProfile`——从而在该 origin 的 cookie 中建立会话,两个窗口共享它。随后 `OauthResult` 以关闭窗口来报告:由本应用打开的窗口中的落地,是登录完成之处,而不是应用该存在之处(否则[启动 gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.zh.md) 会在其中启动一个外壳,而打开它的那个文档已经在等待了)。opener 不标记该窗口:登录从 `aeven.io/oauth/` 开始,其 `Cross-Origin-Opener-Policy: same-origin` 会在返回途中清除 `window.opener` 与 `window.name`,因此两者都没有的落地会通过该 origin 的 `BroadcastChannel` 询问是否有页面正在等待提供方窗口,只有被认领时才关闭;无人认领时它自己进入应用,所以只有一个窗口启动([issue 773](https://github.com/Aeven-AI/Aeven/issues/773))。等待的页面在自己读到会话后仍认领 30 秒,因为落地只在读取 profile 之后才宣告自己。拒绝关闭的浏览器显示已登录提示,而不是第二个外壳。打开该窗口的文档用 `awaitProviderSession()` 等待该会话,反复读取 profile 直到 API 给出一个,随后完全按邮件表单之后的方式继续:读取 profile、离开认证界面,并让 gate 启动。 **被拒绝仍在被拒绝登录所在之处呈现。** 携带错误的落地,或交换失败的落地,会把致歉留在打开它的那个窗口中,与 `redirect` 的呈现一致;本文档继续等待,而读者关闭那个窗口后,仍停留在登录界面、按钮就在手边。 diff --git a/packages/client/ui-auth-aeven/package.json b/packages/client/ui-auth-aeven/package.json index bfc3b88743..8d8a56ae3f 100644 --- a/packages/client/ui-auth-aeven/package.json +++ b/packages/client/ui-auth-aeven/package.json @@ -33,6 +33,7 @@ "devDependencies": { "@aeven/client-ui-primitives": "workspace:^", "@aeven/client-ui-theme": "workspace:^", + "@aeven/util-crypto": "workspace:^", "@deepseek-ai/cordis": "workspace:^", "@types/react": "~18.3.1", "@types/react-dom": "~18.3.0", diff --git a/packages/client/ui-auth-aeven/src/client/auth/services/oauth.ts b/packages/client/ui-auth-aeven/src/client/auth/services/oauth.ts index 6792bd692c..50207be983 100644 --- a/packages/client/ui-auth-aeven/src/client/auth/services/oauth.ts +++ b/packages/client/ui-auth-aeven/src/client/auth/services/oauth.ts @@ -10,7 +10,9 @@ * @module */ +import { randomUUID } from '@aeven/util-crypto' import { getProfile } from './api.ts' +import type { OAuthFlow } from './config.ts' /** How long this document waits between reads of the session. */ const SESSION_POLL_MS = 1000 @@ -48,6 +50,31 @@ export const PROVIDER_SIGN_IN_ENDED_EVENT = 'aeven:provider-sign-in-ended' /** Window features for a provider's consent form. */ const PROVIDER_WINDOW_FEATURES = 'popup=yes,width=520,height=760' +/** Name of the window a provider sign-in opens. */ +const PROVIDER_WINDOW_NAME = 'aeven-provider-signin' + +/** Channel within this origin that a provider landing and the page waiting on it share. */ +const LANDING_CHANNEL = 'aeven-provider-landing' + +/** + * How long a landing that cannot tell whether it is a provider window waits for + * a waiting page to claim it; a waiting page answers within milliseconds. + */ +const LANDING_CLAIM_MS = 1000 + +/** + * How long a page keeps claiming landings after its wait ended on the session: + * the landing announces itself only after its profile read, which can come + * after this page's own read of the session. + */ +const CLAIM_LINGER_MS = 30_000 + +/** What a landing and a waiting page say on {@link LANDING_CHANNEL}. */ +type LandingMessage = { readonly type: 'landed'; readonly id: string } | { readonly type: 'claimed'; readonly id: string } + +/** How a provider landing finishes: it closes and the waiting page boots, or it goes on to the app itself. */ +export type ProviderLandingFinish = 'close' | 'navigate' + /** * Open the provider in a window of its own. * @@ -56,19 +83,75 @@ const PROVIDER_WINDOW_FEATURES = 'popup=yes,width=520,height=760' * @param url - the provider's sign-in URL as the deployment states it. */ export function openProviderSignIn(url: string): void { - window.open(url, 'aeven-provider-signin', PROVIDER_WINDOW_FEATURES) + window.open(url, PROVIDER_WINDOW_NAME, PROVIDER_WINDOW_FEATURES) } /** - * Whether this document is the landing window of a provider sign-in. + * Decide how a provider landing finishes, so exactly one window boots the app. * - * A window this application opened has an opener; a tab the reader navigated - * themselves does not. The landing reports itself by closing, so the - * distinction only decides who closes whom. - * @returns true when another document opened this one. + * A landing that still has its opener or the provider window's name is that + * window. A provider's pages can sever both on the way back (a + * `Cross-Origin-Opener-Policy` switch clears the opener and the name), so under + * the `window` flow a landing that has neither announces itself on + * {@link LANDING_CHANNEL} and closes only when a page waiting on a provider + * window claims it; unclaimed, no page will boot, and it goes on to the app. + * Every landing also announces itself, so the waiting page boots without waiting + * for its next read of the session. A `redirect` landing without an opener is + * the reader's own tab and goes on at once. + * @param flow - the deployment's provider flow. + * @returns `close` when a waiting page boots the app, `navigate` when this landing must. + */ +export async function providerLandingFinish(flow: OAuthFlow): Promise { + const providerWindow = window.opener !== null || window.name === PROVIDER_WINDOW_NAME + if (!providerWindow && flow !== 'window') return 'navigate' + const claimed = await announceLanding(providerWindow ? 0 : LANDING_CLAIM_MS) + return providerWindow || claimed ? 'close' : 'navigate' +} + +/** + * Announce this landing to the pages of this origin. + * @param waitMs - how long to wait for a waiting page's claim. + * @returns whether a waiting page claimed the landing in time; false where the browser has no channel. + */ +function announceLanding(waitMs: number): Promise { + if (typeof BroadcastChannel === 'undefined') return Promise.resolve(false) + const channel = new BroadcastChannel(LANDING_CHANNEL) + const id = randomUUID() + return new Promise((resolve) => { + const settle = (claimed: boolean): void => { + clearTimeout(timer) + channel.close() + resolve(claimed) + } + channel.onmessage = (event: MessageEvent): void => { + if (event.data.type === 'claimed' && event.data.id === id) settle(true) + } + const timer = setTimeout(() => { settle(false) }, waitMs) + channel.postMessage({ type: 'landed', id } satisfies LandingMessage) + }) +} + +/** + * Claim the landings announced on {@link LANDING_CHANNEL} while a provider + * window is out, so they close instead of booting the app a second time. + * @param onLanded - called for a landing while the wait is armed. + * @returns ends the claim: at once for an abandoned wait, after + * {@link CLAIM_LINGER_MS} for one that ended on the session. */ -export function isProviderLanding(): boolean { - return window.opener !== null +function claimLandings(onLanded: () => void): (abandoned: boolean) => void { + if (typeof BroadcastChannel === 'undefined') return () => {} + const channel = new BroadcastChannel(LANDING_CHANNEL) + let armed = true + channel.onmessage = (event: MessageEvent): void => { + if (event.data.type !== 'landed') return + channel.postMessage({ type: 'claimed', id: event.data.id } satisfies LandingMessage) + if (armed) onLanded() + } + return (abandoned) => { + armed = false + if (abandoned) channel.close() + else setTimeout(() => { channel.close() }, CLAIM_LINGER_MS) + } } /** @@ -94,6 +177,8 @@ export async function awaitProviderSession(signal: AbortSignal): Promise { reported = true } window.addEventListener(PROVIDER_SIGNED_IN_EVENT, onReported) + // A landing that announces itself has established the session, as a shell's report has. + const endClaim = claimLandings(() => { window.dispatchEvent(new Event(PROVIDER_SIGNED_IN_EVENT)) }) try { // oxlint-disable-next-line typescript/no-unnecessary-condition -- the abort and sign-in listeners can run during either await. while (!signal.aborted && !reported && !await hasSession()) { @@ -114,6 +199,7 @@ export async function awaitProviderSession(signal: AbortSignal): Promise => api.getProfile().then(() => { - if (oauth.isProviderLanding()) window.close() + const finishMfa = (): Promise => api.getProfile().then(async () => { + if (await oauth.providerLandingFinish(configService.oauthFlow()) === 'close') window.close() else routeService.navigateRoute(referrer || '/') }) diff --git a/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx b/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx index 042f1d69e7..c518e66623 100644 --- a/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx +++ b/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx @@ -2,8 +2,10 @@ * The screen a social sign-in returns to. * * The provider redirects the browser here with either an error or a - * session/challenge pair. A pair is exchanged for a session and the reader is - * sent on to where they came from; anything else leaves the apology on screen. + * session/challenge pair. A pair is exchanged for a session; a provider window + * then closes so the page waiting on it boots the app, and any other landing + * sends the reader on to where they came from. Anything else leaves the apology + * on screen. * Rendering matches the Aeven client exactly. * @module */ @@ -15,7 +17,8 @@ import * as api from '../services/api.ts' import { t } from '../../locales.ts' import * as events from '../services/events.ts' import { navigateRoute, AUTH_ROUTES } from '../services/routes.ts' -import { isProviderLanding } from '../services/oauth.ts' +import { oauthFlow } from '../services/config.ts' +import { providerLandingFinish } from '../services/oauth.ts' import { href } from '../services/utility.ts' import { session, storage } from '../services/session.ts' @@ -39,8 +42,11 @@ function currentReferrer(): string { return storage.getItem('authReferrer') ?? AUTH_ROUTES.home } +/** How long a landing that asked to close stays before it counts the close as refused. */ +const CLOSE_REFUSED_MS = 500 + export function OauthResult(props: OauthResultProps): React.JSX.Element | null { - const [status, setStatus] = useState<'error' | null>(null) + const [status, setStatus] = useState<'error' | 'signed-in' | null>(null) const referrer = useRef(currentReferrer()) useEffect(() => { @@ -69,13 +75,15 @@ export function OauthResult(props: OauthResultProps): React.JSX.Element | null { await api.checkOauthToken(oAuthSession, oAuthChallenge) await api.getProfile() if (cancelled) return - // A landing in a window this application opened is where the sign-in - // finishes, not where the application belongs: the window that opened it - // is waiting on the session this call just established, and it boots the - // shell there. A landing the reader navigated to themselves goes on to - // the screen they came from. - if (isProviderLanding()) { + // A landing in a provider window is where the sign-in finishes, not where + // the application belongs: the page waiting on that window boots the shell. + // A landing no page waits on goes on to the screen the reader came from. + const finish = await providerLandingFinish(oauthFlow()) + if (cancelled) return + if (finish === 'close') { window.close() + // A browser that refuses the close leaves this note, never a second shell. + setTimeout(() => { if (!cancelled) setStatus('signed-in') }, CLOSE_REFUSED_MS) } else { navigateRoute(href(referrer.current)) } @@ -95,15 +103,17 @@ export function OauthResult(props: OauthResultProps): React.JSX.Element | null { }, [props.match.params]) if (status === null) return null + const heading = status === 'error' ? t('oauth.failedHeading') : t('oauth.signedInHeading') + const body = status === 'error' ? t('oauth.failedBody') : t('oauth.signedInBody') return (
- {t('oauth.failedHeading')} + {heading} - {t('oauth.failedBody')} + {body}
diff --git a/packages/client/ui-auth-aeven/src/client/locales.ts b/packages/client/ui-auth-aeven/src/client/locales.ts index 32b8239f67..ef649c7bdb 100644 --- a/packages/client/ui-auth-aeven/src/client/locales.ts +++ b/packages/client/ui-auth-aeven/src/client/locales.ts @@ -130,6 +130,8 @@ export const zh = { 'modal.tooManyCodeAttempts': '你输入错误验证码的次数过多。请 15 分钟后再试', 'oauth.failedHeading': '出错了!', 'oauth.failedBody': '你好,似乎出了点问题。请重试', + 'oauth.signedInHeading': '已登录', + 'oauth.signedInBody': 'Æven 会在你开始登录的窗口中继续。可以关闭此窗口了。', 'name.title': '你好!', 'name.prompt': '在我们开始聊天之前,我该怎么称呼你?', 'name.promptAnonymous': '在我这里你不必匿名 ;)', @@ -256,6 +258,8 @@ export const en: Record = { 'modal.tooManyCodeAttempts': 'You entered a wrong code too many times. Please try again in 15 minutes', 'oauth.failedHeading': 'Oops!', 'oauth.failedBody': 'Hi, It seems i have an issue. Please try again', + 'oauth.signedInHeading': 'You’re signed in', + 'oauth.signedInBody': 'Æven continues in the window you started from. You can close this window.', 'name.title': 'Hi there!', 'name.prompt': 'Before we continue to chat, how should I call you?', 'name.promptAnonymous': "You don't have to be anonymous with me ;)", @@ -382,6 +386,8 @@ export const es: Record = { 'modal.tooManyCodeAttempts': 'Introdujiste un código incorrecto demasiadas veces. Inténtalo de nuevo en 15 minutos', 'oauth.failedHeading': '¡Vaya!', 'oauth.failedBody': 'Hola, parece que tengo un problema. Inténtalo de nuevo', + 'oauth.signedInHeading': 'Sesión iniciada', + 'oauth.signedInBody': 'Æven continúa en la ventana desde la que empezaste. Puedes cerrar esta ventana.', 'name.title': '¡Hola!', 'name.prompt': 'Antes de seguir chateando, ¿cómo quieres que te llame?', 'name.promptAnonymous': 'Conmigo no tienes que ser anónimo ;)', diff --git a/packages/client/ui-auth-aeven/tests/oauth.client.spec.ts b/packages/client/ui-auth-aeven/tests/oauth.client.spec.ts index 223af4841d..c81b7586bc 100644 --- a/packages/client/ui-auth-aeven/tests/oauth.client.spec.ts +++ b/packages/client/ui-auth-aeven/tests/oauth.client.spec.ts @@ -8,7 +8,7 @@ */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { - awaitProviderSession, isProviderLanding, openProviderSignIn, PROVIDER_SIGNED_IN_EVENT, + awaitProviderSession, openProviderSignIn, PROVIDER_SIGNED_IN_EVENT, providerLandingFinish, } from '../src/client/auth/services/oauth.ts' /** The grant a session read refreshes in through; only its arrival is read. */ @@ -30,6 +30,27 @@ function scriptedApi(state: { signedIn: boolean; reachable?: boolean }): void { })) } +/** + * Give this test its own same-origin channels: each message reaches the other + * open channels of its name in a microtask, and a wait an earlier test left + * lingering belongs to that test's channels, not this one's. + */ +function isolatedChannels(): void { + const open = new Set() + class FakeChannel { + onmessage: ((event: MessageEvent) => void) | null = null + constructor(readonly name: string) { open.add(this) } + postMessage(data: unknown): void { + for (const other of open) { + if (other === this || other.name !== this.name) continue + queueMicrotask(() => { if (open.has(other)) other.onmessage?.(new MessageEvent('message', { data })) }) + } + } + close(): void { open.delete(this) } + } + vi.stubGlobal('BroadcastChannel', FakeChannel) +} + /** Install an opener, or restore the null one jsdom leaves. */ function withOpener(opener: object | null): void { Object.defineProperty(window, 'opener', { value: opener, configurable: true, writable: true }) @@ -39,6 +60,8 @@ beforeEach(() => { ;(globalThis as { __AVN_AEVEN__?: unknown }).__AVN_AEVEN__ = { apiUrl: 'http://api.test' } window.localStorage.clear() withOpener(null) + window.name = '' + isolatedChannels() }) afterEach(() => { @@ -62,10 +85,49 @@ describe('the provider window', () => { ) }) - it('is this document only when another document opened it', () => { - expect(isProviderLanding()).toBe(false) +}) + +describe('finishing a provider landing in exactly one window', () => { + it('closes a landing that still has its opener or the provider window\'s name', async () => { withOpener({}) - expect(isProviderLanding()).toBe(true) + await expect(providerLandingFinish('window')).resolves.toBe('close') + withOpener(null) + window.name = 'aeven-provider-signin' + await expect(providerLandingFinish('redirect')).resolves.toBe('close') + }) + + it('sends a redirect landing without an opener on to the app at once', async () => { + const started = Date.now() + await expect(providerLandingFinish('redirect')).resolves.toBe('navigate') + expect(Date.now() - started).toBeLessThan(100) + }) + + it('closes a severed window-flow landing that the waiting page claims, and that page boots', async () => { + scriptedApi({ signedIn: false }) + const waiting = awaitProviderSession(new AbortController().signal) + + await expect(providerLandingFinish('window')).resolves.toBe('close') + await expect(waiting).resolves.toBe(true) + }) + + it('still claims a landing that announces itself after the page already read the session', async () => { + scriptedApi({ signedIn: true }) + await expect(awaitProviderSession(new AbortController().signal)).resolves.toBe(true) + + await expect(providerLandingFinish('window')).resolves.toBe('close') + }) + + it('goes on to the app from a severed window-flow landing that no page waits on', async () => { + const attempt = new AbortController() + scriptedApi({ signedIn: false }) + const waiting = awaitProviderSession(attempt.signal) + attempt.abort() + await waiting + vi.useFakeTimers() + + const finishing = providerLandingFinish('window') + await vi.advanceTimersByTimeAsync(1000) + await expect(finishing).resolves.toBe('navigate') }) }) diff --git a/packages/client/ui-auth-aeven/tsconfig.json b/packages/client/ui-auth-aeven/tsconfig.json index 8a5ce3da09..420bce82b3 100644 --- a/packages/client/ui-auth-aeven/tsconfig.json +++ b/packages/client/ui-auth-aeven/tsconfig.json @@ -16,6 +16,9 @@ { "path": "../ui-theme" }, + { + "path": "../../util/crypto" + }, { "path": "../../../vendor/cordis" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f963835f24..e1bfe212cd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3132,6 +3132,9 @@ importers: '@aeven/client-ui-theme': specifier: workspace:^ version: link:../ui-theme + '@aeven/util-crypto': + specifier: workspace:^ + version: link:../../util/crypto '@deepseek-ai/cordis': specifier: workspace:^ version: link:../../../vendor/cordis From 0bcde46872d6758f175a2c942be21750ecb1359f Mon Sep 17 00:00:00 2001 From: olibaron Date: Mon, 23 Nov 2026 21:21:45 +0100 Subject: [PATCH 2/3] feat(ui-conversation): archive a session from the header options (#774) On a phone the sidebar rows' options never show, so a Session could not be archived there. The conversation header's Options menu now offers "Archive session" right after "Export session", running the same workspace archive the row menu runs; an archived Session offers "Unarchive session" in its place, as its row does. zh/en/es. Closes #774 Co-Authored-By: Claude Opus 5.5 --- .../ui-conversation/src/client/apply.ts | 16 +++++++++ .../src/client/contract/slots.ts | 9 +++++ .../ui-conversation/src/client/locales.ts | 6 ++++ .../client/skeleton/ConversationSession.tsx | 8 +++-- .../src/client/skeleton/NavigationOptions.tsx | 23 ++++++++++--- .../tests/skeleton.client.spec.tsx | 34 ++++++++++++++++++- .../ui-trajectory/tests/views.client.spec.tsx | 3 ++ 7 files changed, 92 insertions(+), 7 deletions(-) diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 5a96599cb6..916840428e 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -339,6 +339,7 @@ export function apply(ctx: Context): void { conversationViews, selectedView: uiConversation.binding(sessionId).selectedView, moveTargets: workspaceNavigation.moveTargets?.(sessionId) ?? ABSENT_MOVE_TARGETS, + archivedSessionIds: workspaceNavigation.archivedSessionIds ?? ABSENT_ARCHIVED, }, open: (id) => { sessions.open(id) }, // The Session's lifecycle actions the header offers, as its row menu runs @@ -368,6 +369,21 @@ export function apply(ctx: Context): void { // Move failure keeps the current selection, as a failed fork does. }) }, + // Archive and unarchive commit directly and log a rejection, as the Session's row menu does. + archiveSession: workspaceNavigation.archiveSession === undefined + ? undefined + : () => { + workspaceNavigation.archiveSession?.(sessionId).catch((reason: unknown) => { + console.warn('session archive rejected:', reason) + }) + }, + unarchiveSession: workspaceNavigation.unarchiveSession === undefined + ? undefined + : () => { + workspaceNavigation.unarchiveSession?.(sessionId).catch((reason: unknown) => { + console.warn('session unarchive rejected:', reason) + }) + }, selectView: (view) => { activateView(sessionId, view) actions.setView(view) diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index b96018c2ee..718521b661 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -338,6 +338,8 @@ export interface ConversationSessionHeaderInjected { readonly selectedView: ObservableSnapshot /** Workspaces this Session can move into, in list order. */ readonly moveTargets: ObservableSnapshot + /** The registry-global archive set, which decides whether the options offer archive or unarchive. */ + readonly archivedSessionIds: ObservableSnapshot } /** Select a Session through the Session Controller. */ open: (sessionId: SessionId) => void @@ -350,6 +352,13 @@ export interface ConversationSessionHeaderInjected { * replaces it; absent in an assembly without a Workspace surface. */ moveSession: ((workspaceId: WorkspaceId) => void) | undefined + /** + * Archive this Session into the registry-global hidden set, as its row menu does; absent in an assembly without a + * Workspace surface. + */ + archiveSession: (() => void) | undefined + /** Restore this archived Session, as its row menu does; absent in an assembly without a Workspace surface. */ + unarchiveSession: (() => void) | undefined /** * The moves between the account's devices this Host offers for this Session, read when the options open; a * Session that is not synced, or a Host that is always on, offers none. diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index fbd07977a2..cc85c95b5a 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -26,6 +26,8 @@ export const zh = { 'nav.options': '选项', 'nav.fork': '分叉会话', 'nav.export': '导出会话', + 'nav.archive': '归档会话', + 'nav.unarchive': '取消归档', 'nav.move': '移动到工作区', 'nav.chooseDesktop': '选择桌面设备', 'desktops.title': '在桌面设备上继续', @@ -291,6 +293,8 @@ export const en = { 'nav.options': 'Options', 'nav.fork': 'Fork session', 'nav.export': 'Export session', + 'nav.archive': 'Archive session', + 'nav.unarchive': 'Unarchive session', 'nav.move': 'Move to workspace', 'nav.chooseDesktop': 'Choose desktop', 'desktops.title': 'Continue on a desktop', @@ -557,6 +561,8 @@ export const es = { 'nav.options': 'Opciones', 'nav.fork': 'Bifurcar sesión', 'nav.export': 'Exportar sesión', + 'nav.archive': 'Archivar sesión', + 'nav.unarchive': 'Desarchivar sesión', 'nav.move': 'Mover a espacio de trabajo', 'nav.chooseDesktop': 'Elegir escritorio', 'desktops.title': 'Continuar en un escritorio', diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx index b0fbdf4fed..3d70fa60eb 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx @@ -26,13 +26,15 @@ export type ConversationSessionHeaderProps = ConversationSessionHeaderSlotProps * @returns the header row. */ export function ConversationSessionHeader({ - sessionId, useSessions, useConversationViews, useSelectedView, useMoveTargets, useStore, renderSlot, - forkSession, exportSession, moveSession, devicePlacement, continueOn, selectView, t, + sessionId, useSessions, useConversationViews, useSelectedView, useMoveTargets, useArchivedSessionIds, useStore, + renderSlot, forkSession, exportSession, moveSession, archiveSession, unarchiveSession, devicePlacement, continueOn, + selectView, t, }: ConversationSessionHeaderProps) { const displayTitle = useSessions(state => state.byId[sessionId]?.displayTitle) const views = useConversationViews(value => value) const selectedView = useSelectedView(value => value) const moveTargets = useMoveTargets(value => value) + const archived = useArchivedSessionIds(ids => ids.includes(sessionId)) const running = useSessions(state => state.byId[sessionId]?.running) ?? false // The resolved View is what the reader is looking at; the stored preference // answers before the Session's binding has activated one. @@ -49,6 +51,8 @@ export function ConversationSessionHeader({ onSelect={selectView} onFork={forkSession} onExport={exportSession} + onArchive={archived ? undefined : archiveSession} + onUnarchive={archived ? unarchiveSession : undefined} moveTargets={moveSession === undefined ? [] : moveTargets} moveDisabled={running} onMove={moveSession ?? (() => {})} diff --git a/packages/client/ui-conversation/src/client/skeleton/NavigationOptions.tsx b/packages/client/ui-conversation/src/client/skeleton/NavigationOptions.tsx index c032b7e559..e12c192bdb 100644 --- a/packages/client/ui-conversation/src/client/skeleton/NavigationOptions.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/NavigationOptions.tsx @@ -15,7 +15,7 @@ */ import { useState } from 'react' import { - Button, IconBranchOutline16, IconDownloadOutline16, IconInspectOutline12, IconLucideEllipsisVertical, + Button, IconArchiveOutline20, IconBranchOutline16, IconDownloadOutline16, IconInspectOutline12, IconLucideEllipsisVertical, IconLucideFolder, IconLucideLaptopMinimal, IconLucideMessageCircle, Menu, Modal, Tooltip, type MenuEntry, } from '@aeven/client-ui-primitives' import type { WorkspaceId } from '@aeven/workspace/types' @@ -52,6 +52,10 @@ export interface NavigationOptionsProps { onFork: () => void /** Download this Session's complete history as a ZIP archive. */ onExport: () => Promise + /** Archive this Session; absent hides the row, as for an archived Session. */ + onArchive: (() => void) | undefined + /** Restore this archived Session; present only while it is archived, in place of archive. */ + onUnarchive: (() => void) | undefined /** Workspaces this Session can move into; empty hides the move row. */ moveTargets: readonly SessionMoveTarget[] /** Whether a move cannot start now, such as while a turn runs. */ @@ -72,7 +76,8 @@ export interface NavigationOptionsProps { * @returns the options anchor with its conditional foldout, or null when no View lies beyond the current one. */ export function NavigationOptions({ - views, activeId, onSelect, onFork, onExport, moveTargets, moveDisabled, onMove, devicePlacement, onContinueOn, t, + views, activeId, onSelect, onFork, onExport, onArchive, onUnarchive, moveTargets, moveDisabled, onMove, + devicePlacement, onContinueOn, t, }: NavigationOptionsProps) { const [open, setOpen] = useState(false) // Read each time the options open, so a turn that ran on another device since shows its move. @@ -91,11 +96,19 @@ export function NavigationOptions({ void onExport().catch(fail) } // The Session's own actions, in the order its row menu lists them (fork), - // then the export, the desktop choice, the move destinations and the other device moves, followed by the Views - // the reader is not in. + // then the export, archive or unarchive as the row menu offers it, the + // desktop choice, the move destinations and the other device moves, followed + // by the Views the reader is not in. const items: MenuEntry[] = [ { id: 'fork', label: t('nav.fork'), icon: }, { id: 'export', label: t('nav.export'), icon: }, + // 20-native glyph in the menu's 16px icon slot, as the row menu draws it. + ...onArchive === undefined + ? [] + : [{ id: 'archive', label: t('nav.archive'), icon: }], + ...onUnarchive === undefined + ? [] + : [{ id: 'unarchive', label: t('nav.unarchive'), icon: }], ...placement.desktops === undefined ? [] : [{ @@ -138,6 +151,8 @@ export function NavigationOptions({ setOpen(false) if (id === 'fork') onFork() else if (id === 'export') runExport() + else if (id === 'archive') onArchive?.() + else if (id === 'unarchive') onUnarchive?.() else if (id.startsWith(MOVE_PREFIX)) onMove(id.slice(MOVE_PREFIX.length) as WorkspaceId) else if (id === 'choose-desktop') setChoosing(true) // A remaining id is a View: the roster supplies exactly those. diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 23df902126..bf05f19cdb 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -198,6 +198,8 @@ function mount( workspacePhase?: WorkspaceSnapshot['phase'] /** No session selected — cold start, or the list has yet to restore one. */ noSelection?: boolean + /** The selected session sits in the archive set. */ + archived?: boolean /** Override the selected Session identity. */ sessionId?: SessionId /** Left navigation column fold state the frame hands the shell. */ @@ -252,6 +254,9 @@ function mount( const inputActions = wiring.actions const stop = vi.fn() const open = vi.fn() + const archiveSession = vi.fn() + const unarchiveSession = vi.fn() + const archivedIds: readonly SessionId[] = options.archived === true ? [SID] : [] const slotCalls: string[] = [] const lineageOwners: ConversationHeaderLineageOwnerProps[] = [] const viewTabs = options.viewTabs ?? [ @@ -283,6 +288,7 @@ function mount( useConversationViews={useConversationViews} useSelectedView={useSelectedView} useMoveTargets={bindSnapshotSelector(createSnapshotStore([]))} + useArchivedSessionIds={select => select(archivedIds)} useChat={useChat} useTrajectory={useTrajectory} useSessions={props.useSessions} @@ -300,6 +306,8 @@ function mount( devicePlacement={() => Promise.resolve({})} continueOn={() => Promise.resolve()} moveSession={undefined} + archiveSession={archiveSession} + unarchiveSession={unarchiveSession} selectView={(view) => { store.actions.setView(view) }} t={t} /> @@ -398,7 +406,7 @@ function mount( startPage: path => options.startPage?.address === path ? { key: options.startPage.key, composer: options.startPage.composer, composerPlaceholder: options.startPage.composerPlaceholder } : undefined, - useArchivedSessionIds: select => select([]), + useArchivedSessionIds: select => select(archivedIds), useInput, inputActions, renderSlot, @@ -412,6 +420,7 @@ function mount( flushAnimationFrames(2) return { view, store, wiring, sink, retargetWorkspace, session, conversation, slotCalls, lineageOwners, seatOwners, open, + archiveSession, unarchiveSession, pickerOwner: () => pickerOwner, rerender: (patch?: Partial>) => { Object.assign(props, patch) @@ -949,6 +958,29 @@ describe('ConversationRoot resident composer', () => { expect(rows).not.toContain('查看Chat') }) + it('offers archive right after export in the header options, and archives this session', () => { + const b = mount(sessionSnapshotOf()) + fireEvent.click(b.view.getByLabelText('选项')) + const rows = b.view.getAllByRole('menuitem').map(row => row.textContent) + expect(rows.indexOf('归档会话')).toBe(rows.indexOf('导出会话') + 1) + expect(rows).not.toContain('取消归档') + + fireEvent.click(b.view.getByRole('menuitem', { name: '归档会话' })) + expect(b.archiveSession).toHaveBeenCalledOnce() + expect(b.unarchiveSession).not.toHaveBeenCalled() + }) + + it('offers unarchive in place of archive for an archived session', () => { + const b = mount(sessionSnapshotOf(), undefined, undefined, { archived: true }) + fireEvent.click(b.view.getByLabelText('选项')) + const rows = b.view.getAllByRole('menuitem').map(row => row.textContent) + expect(rows.indexOf('取消归档')).toBe(rows.indexOf('导出会话') + 1) + expect(rows).not.toContain('归档会话') + + fireEvent.click(b.view.getByRole('menuitem', { name: '取消归档' })) + expect(b.unarchiveSession).toHaveBeenCalledOnce() + }) + it('keeps the Hero composer usable while the workspace list has not settled', () => { // The Hero no longer names a workspace, so the only thing the owning // Workspace still answers is whether the composer is inert. While the list diff --git a/packages/client/ui-trajectory/tests/views.client.spec.tsx b/packages/client/ui-trajectory/tests/views.client.spec.tsx index 98b5543599..829cbc568b 100644 --- a/packages/client/ui-trajectory/tests/views.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.client.spec.tsx @@ -386,6 +386,7 @@ function mount(fixture: Awaited>) { useConversationViews, useSelectedView: bindSnapshotSelector(selectedView), useMoveTargets: bindSnapshotSelector(createSnapshotStore([])), + useArchivedSessionIds: bindSnapshotSelector(createSnapshotStore([])), useSessions, useSessionPendingInteraction, useWorkspaces, @@ -439,6 +440,8 @@ function mount(fixture: Awaited>) { devicePlacement={() => Promise.resolve({})} continueOn={() => Promise.resolve()} moveSession={undefined} + archiveSession={undefined} + unarchiveSession={undefined} selectView={conversation.actions.setView} t={tConversation} /> From 94b5ddfd6d0a7072752625de5e5910fb41ade22e Mon Sep 17 00:00:00 2001 From: olibaron Date: Mon, 23 Nov 2026 21:26:22 +0100 Subject: [PATCH 3/3] fix(ui-auth-aeven): name the cancellation re-check after the landing decision Co-Authored-By: Claude Opus 5.5 --- .../client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx b/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx index c518e66623..c05d701314 100644 --- a/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx +++ b/packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx @@ -79,6 +79,7 @@ export function OauthResult(props: OauthResultProps): React.JSX.Element | null { // the application belongs: the page waiting on that window boots the shell. // A landing no page waits on goes on to the screen the reader came from. const finish = await providerLandingFinish(oauthFlow()) + // oxlint-disable-next-line typescript/no-unnecessary-condition -- the effect's cleanup can run during the await. if (cancelled) return if (finish === 'close') { window.close()