From 21aa706c26ca00b076073b31825b53443adbbfdb Mon Sep 17 00:00:00 2001
From: "Fredrik Liljegren (Claude Code Opus 5.5)"
Date: Tue, 10 Nov 2026 09:34:59 +0100
Subject: [PATCH 1/3] fix: an expired IAP sign-in reloads the page instead of
failing every background request
Background requests use redirect: 'manual', so IAP's redirect to Google is seen as a sign-out. The page
reloads once when nothing would be lost, and otherwise says to reload.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Bwp5QefjsjMFeq6CK6cT6w
---
packages/server/src/html.ts | 43 +++++++--
packages/server/tests/http.test.ts | 4 +
.../components/layout/signed-out-banner.tsx | 41 ++++++++
packages/ui/src/hooks/use-tab-badge.ts | 3 +-
packages/ui/src/lib/api.ts | 9 +-
packages/ui/src/lib/request.ts | 14 +++
packages/ui/src/lib/sign-in.ts | 71 ++++++++++++++
packages/ui/src/root.tsx | 2 +
packages/ui/tests/sign-in.test.tsx | 96 +++++++++++++++++++
9 files changed, 272 insertions(+), 11 deletions(-)
create mode 100644 packages/ui/src/components/layout/signed-out-banner.tsx
create mode 100644 packages/ui/src/lib/request.ts
create mode 100644 packages/ui/src/lib/sign-in.ts
create mode 100644 packages/ui/tests/sign-in.test.tsx
diff --git a/packages/server/src/html.ts b/packages/server/src/html.ts
index cd86043c..543a061c 100644
--- a/packages/server/src/html.ts
+++ b/packages/server/src/html.ts
@@ -89,12 +89,16 @@ const RELOAD_ICON = `
`;
}
/**
* Keeps the sessions page current without reloading it: swaps in `/sessions/body` every minute while the tab
* is visible, and from GitHub rather than the server's cache when the reload button asks. Needs SECTIONS_SCRIPT.
+ *
+ * An expired IAP sign-in answers with a redirect to Google, which a fetch cannot follow; only reloading the page
+ * signs in again. That happens on its own unless the reader is typing or away, and at most once per page load.
*/
export const SESSIONS_SCRIPT = `(() => {
const AUTO_MS = 60000;
@@ -102,10 +106,28 @@ export const SESSIONS_SCRIPT = `(() => {
const age = document.getElementById('sessions-age');
const error = document.getElementById('sessions-error');
const reload = document.getElementById('sessions-reload');
- if (!container || !age || !error || !reload) return;
+ const signedOutNote = document.getElementById('sessions-signed-out');
+ if (!container || !age || !error || !reload || !signedOutNote) return;
let loadedAt = Date.now();
let inFlight = false;
let failed = false;
+ let signedOut = false;
+ let reloaded = false;
+
+ const typing = () => {
+ const active = document.activeElement;
+ return !!active && (active.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName));
+ };
+ const signOut = () => {
+ signedOut = true;
+ if (!reloaded && document.visibilityState === 'visible' && !typing()) {
+ reloaded = true;
+ location.reload();
+ return;
+ }
+ age.hidden = true;
+ signedOutNote.hidden = false;
+ };
const formatAge = ${formatAge.toString()};
const tick = () => {
@@ -114,13 +136,17 @@ export const SESSIONS_SCRIPT = `(() => {
};
const refresh = async fresh => {
- if (inFlight) return;
+ if (inFlight || signedOut) return;
// Swapping the content would take focus from the control a keyboard user is on; the next tick tries again.
if (!fresh && container.contains(document.activeElement)) return;
inFlight = true;
reload.setAttribute('aria-busy', 'true');
try {
- const res = await fetch('/sessions/body' + (fresh ? '?fresh=1' : ''), { credentials: 'same-origin', cache: 'no-store' });
+ const res = await fetch('/sessions/body' + (fresh ? '?fresh=1' : ''), { credentials: 'same-origin', cache: 'no-store', redirect: 'manual' });
+ if (res.type === 'opaqueredirect' || res.status === 401) {
+ signOut();
+ return;
+ }
if (!res.ok) throw new Error('HTTP ' + res.status);
const template = document.createElement('template');
template.innerHTML = await res.text();
@@ -135,19 +161,24 @@ export const SESSIONS_SCRIPT = `(() => {
} finally {
inFlight = false;
reload.removeAttribute('aria-busy');
- error.hidden = !failed;
+ error.hidden = !failed || signedOut;
tick();
}
};
const due = () => failed || Date.now() - loadedAt >= AUTO_MS;
- reload.addEventListener('click', () => refresh(true));
+ reload.addEventListener('click', () => {
+ if (signedOut) location.reload();
+ else refresh(true);
+ });
setInterval(() => {
tick();
if (document.visibilityState === 'visible' && due()) refresh(false);
}, 15000);
document.addEventListener('visibilitychange', () => {
- if (document.visibilityState === 'visible' && due()) refresh(false);
+ if (document.visibilityState !== 'visible') return;
+ if (signedOut) signOut();
+ else if (due()) refresh(false);
});
})();
`;
diff --git a/packages/server/tests/http.test.ts b/packages/server/tests/http.test.ts
index b700051e..51614c30 100644
--- a/packages/server/tests/http.test.ts
+++ b/packages/server/tests/http.test.ts
@@ -469,6 +469,10 @@ describe('pull requests awaiting review', () => {
expect(sessionsScript.headers.get('content-type')).toContain('javascript');
expect(sessionsScript.body).toContain("'/sessions/body' + (fresh ? '?fresh=1' : '')");
expect(sessionsScript.body).toContain('applySections(template.content)');
+ expect(sessionsScript.body).toContain("redirect: 'manual'");
+ expect(sessionsScript.body).toContain("res.type === 'opaqueredirect' || res.status === 401");
+ expect(sessionsScript.body).toContain('location.reload()');
+ expect(page).toContain('Signed out · reload to sign in again');
const script = await api('/sections.js');
expect(script.headers.get('content-type')).toContain('javascript');
expect(script.body).toContain('localStorage');
diff --git a/packages/ui/src/components/layout/signed-out-banner.tsx b/packages/ui/src/components/layout/signed-out-banner.tsx
new file mode 100644
index 00000000..30ab43f5
--- /dev/null
+++ b/packages/ui/src/components/layout/signed-out-banner.tsx
@@ -0,0 +1,41 @@
+import { useEffect, useSyncExternalStore } from 'react';
+import { isSignedOut, reloadIfSafe, subscribeSignedOut } from '../../lib/sign-in';
+
+export function SignedOutBanner() {
+ const signedOut = useSyncExternalStore(subscribeSignedOut, isSignedOut, () => false);
+
+ useEffect(() => {
+ if (!signedOut) {
+ return;
+ }
+ reloadIfSafe();
+ const onVisibility = () => {
+ if (document.visibilityState === 'visible') {
+ reloadIfSafe();
+ }
+ };
+ document.addEventListener('visibilitychange', onVisibility);
+ return () => document.removeEventListener('visibilitychange', onVisibility);
+ }, [signedOut]);
+
+ if (!signedOut) {
+ return null;
+ }
+
+ return (
+
+ Your sign-in expired. Reload to sign in again.
+
+
+ );
+}
diff --git a/packages/ui/src/hooks/use-tab-badge.ts b/packages/ui/src/hooks/use-tab-badge.ts
index 1fee8226..96f9ff3e 100644
--- a/packages/ui/src/hooks/use-tab-badge.ts
+++ b/packages/ui/src/hooks/use-tab-badge.ts
@@ -1,5 +1,6 @@
import { useEffect, useRef } from 'react';
import { addBadge, titleWithCount, toHref } from '../lib/favicon-badge';
+import { apiRequest } from '../lib/request';
/** Marks the browser tab and its title while `count` answers wait unseen. */
export function useTabBadge(count: number): void {
@@ -37,7 +38,7 @@ export function useTabBadge(count: number): void {
if (plainSvg.current !== null) {
badge(plainSvg.current);
} else {
- void fetch(href)
+ void apiRequest(href)
.then(res => (res.ok ? res.text() : Promise.reject(new Error(res.statusText))))
.then(svg => {
plainSvg.current = svg;
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index f9a8e8f3..cee92083 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -17,6 +17,7 @@ import type {
Tour,
} from '@diffity/api';
import { apiPath } from './base';
+import { apiRequest } from './request';
export type {
GitHubDetails,
@@ -29,7 +30,7 @@ export type {
} from '@diffity/api';
async function apiFetch(url: string, init?: RequestInit): Promise {
- const res = await fetch(apiPath(url), init);
+ const res = await apiRequest(apiPath(url), init);
if (!res.ok) {
throw new Error(await errorMessage(res));
}
@@ -37,7 +38,7 @@ async function apiFetch(url: string, init?: RequestInit): Promise {
}
async function apiVoid(url: string, init?: RequestInit): Promise {
- const res = await fetch(apiPath(url), init);
+ const res = await apiRequest(apiPath(url), init);
if (!res.ok) {
throw new Error(await errorMessage(res));
}
@@ -71,7 +72,7 @@ export function fetchRepoInfo(): Promise {
}
export async function fetchThreads(sessionId: string, status?: ThreadStatus): Promise {
- const res = await fetch(apiPath(buildUrl('/api/threads', { session: sessionId, status })));
+ const res = await apiRequest(apiPath(buildUrl('/api/threads', { session: sessionId, status })));
if (!res.ok) {
return [];
}
@@ -135,7 +136,7 @@ export async function fetchFileContent(filePath: string): Promise {
}
export async function fetchGitHubDetails(): Promise {
- const res = await fetch(apiPath('/api/github/details'));
+ const res = await apiRequest(apiPath('/api/github/details'));
if (!res.ok) {
return null;
}
diff --git a/packages/ui/src/lib/request.ts b/packages/ui/src/lib/request.ts
new file mode 100644
index 00000000..4ef3bd31
--- /dev/null
+++ b/packages/ui/src/lib/request.ts
@@ -0,0 +1,14 @@
+import { markSignedOut } from './sign-in';
+
+/**
+ * The server never redirects these requests; a redirect is IAP sending an expired sign-in to Google, which
+ * a fetch cannot follow.
+ */
+export async function apiRequest(url: string, init?: RequestInit): Promise {
+ const res = await fetch(url, { ...init, redirect: 'manual' });
+ if (res.type === 'opaqueredirect') {
+ markSignedOut();
+ throw new Error('Signed out');
+ }
+ return res;
+}
diff --git a/packages/ui/src/lib/sign-in.ts b/packages/ui/src/lib/sign-in.ts
new file mode 100644
index 00000000..ab386a4f
--- /dev/null
+++ b/packages/ui/src/lib/sign-in.ts
@@ -0,0 +1,71 @@
+let signedOut = false;
+let reloaded = false;
+const listeners = new Set<() => void>();
+
+export function isSignedOut(): boolean {
+ return signedOut;
+}
+
+export function markSignedOut(): void {
+ if (signedOut) {
+ return;
+ }
+ signedOut = true;
+ for (const listener of listeners) {
+ listener();
+ }
+}
+
+export function subscribeSignedOut(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+export interface PageState {
+ visible: boolean;
+ /** Something the reader typed that a reload would throw away. */
+ hasDraft: boolean;
+ editing: boolean;
+}
+
+export function shouldAutoReload(state: PageState, alreadyReloaded: boolean): boolean {
+ return !alreadyReloaded && state.visible && !state.hasDraft && !state.editing;
+}
+
+const TEXT_INPUT_TYPES = new Set(['', 'text', 'search', 'email', 'url', 'tel', 'password', 'number']);
+
+export function readPageState(doc: Document = document): PageState {
+ const fields = [
+ ...doc.querySelectorAll('textarea'),
+ ...[...doc.querySelectorAll('input')].filter(input => TEXT_INPUT_TYPES.has(input.getAttribute('type')?.toLowerCase() ?? '')),
+ ];
+ const active = doc.activeElement;
+ const editing = active instanceof HTMLElement
+ && (active.isContentEditable || active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement || active instanceof HTMLSelectElement);
+ return {
+ visible: doc.visibilityState === 'visible',
+ hasDraft: fields.some(field => field.value.trim() !== ''),
+ editing,
+ };
+}
+
+/**
+ * An expired IAP sign-in can only be renewed by loading the page again. Does that once per page load, and
+ * only when nothing the reader is in the middle of would be lost.
+ */
+export function reloadIfSafe(reload: () => void = () => window.location.reload(), state: PageState = readPageState()): boolean {
+ if (!shouldAutoReload(state, reloaded)) {
+ return false;
+ }
+ reloaded = true;
+ reload();
+ return true;
+}
+
+export function resetSignInForTests(): void {
+ signedOut = false;
+ reloaded = false;
+ listeners.clear();
+}
diff --git a/packages/ui/src/root.tsx b/packages/ui/src/root.tsx
index 806c23c7..0a24ff27 100644
--- a/packages/ui/src/root.tsx
+++ b/packages/ui/src/root.tsx
@@ -5,6 +5,7 @@ import { Toaster } from "sonner";
import NProgress from "nprogress";
import { queryClient } from "./lib/query-client";
import { ErrorPage } from "./components/error-page";
+import { SignedOutBanner } from "./components/layout/signed-out-banner";
import { pagePath } from "./lib/base";
import "nprogress/nprogress.css";
import "./styles/app.css";
@@ -57,6 +58,7 @@ export default function App() {
+
{
+ resetSignInForTests();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+const CLEAN = { visible: true, hasDraft: false, editing: false };
+
+describe('the request helper', () => {
+ it('asks not to follow redirects and passes a normal response through', async () => {
+ const response = new Response('{}', { status: 200 });
+ const fetchMock = vi.fn().mockResolvedValue(response);
+ vi.stubGlobal('fetch', fetchMock);
+
+ expect(await apiRequest('/api/info', { method: 'POST' })).toBe(response);
+ expect(fetchMock).toHaveBeenCalledWith('/api/info', { method: 'POST', redirect: 'manual' });
+ expect(isSignedOut()).toBe(false);
+ });
+
+ it('passes an error response through for the caller to handle', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('', { status: 500 })));
+
+ expect((await apiRequest('/api/info')).status).toBe(500);
+ expect(isSignedOut()).toBe(false);
+ });
+
+ it('marks the page signed out and rejects on a redirect', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ type: 'opaqueredirect', status: 0, ok: false } as Response));
+
+ await expect(apiRequest('/api/info')).rejects.toThrow('Signed out');
+ expect(isSignedOut()).toBe(true);
+ });
+});
+
+describe('reloading after the sign-in expired', () => {
+ it('reloads a visible page with nothing typed', () => {
+ expect(shouldAutoReload(CLEAN, false)).toBe(true);
+ });
+
+ it('leaves a page with a draft, a focused field or a hidden tab alone', () => {
+ expect(shouldAutoReload({ ...CLEAN, hasDraft: true }, false)).toBe(false);
+ expect(shouldAutoReload({ ...CLEAN, editing: true }, false)).toBe(false);
+ expect(shouldAutoReload({ ...CLEAN, visible: false }, false)).toBe(false);
+ });
+
+ it('reloads only once', () => {
+ const reload = vi.fn();
+ expect(reloadIfSafe(reload, CLEAN)).toBe(true);
+ expect(reloadIfSafe(reload, CLEAN)).toBe(false);
+ expect(reload).toHaveBeenCalledTimes(1);
+ });
+
+ it('counts typed text as a draft, and a focused field as editing', () => {
+ const textarea = document.createElement('textarea');
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ document.body.append(textarea, checkbox);
+ expect(readPageState()).toMatchObject({ hasDraft: false, editing: false });
+
+ textarea.value = 'half a comment';
+ expect(readPageState().hasDraft).toBe(true);
+
+ textarea.value = '';
+ textarea.focus();
+ expect(readPageState().editing).toBe(true);
+ });
+});
+
+describe('the signed-out banner', () => {
+ it('shows nothing while signed in', () => {
+ render();
+ expect(screen.queryByTestId('signed-out-banner')).toBeNull();
+ });
+
+ it('offers a reload instead of reloading over a draft', () => {
+ const textarea = document.createElement('textarea');
+ textarea.value = 'unsent';
+ document.body.append(textarea);
+ render();
+
+ act(() => markSignedOut());
+
+ expect(screen.getByTestId('signed-out-banner').textContent).toContain('Your sign-in expired. Reload to sign in again.');
+ expect(screen.getByRole('button', { name: 'Reload' })).toBeTruthy();
+ });
+});
From 4609236751f290111a5ae1fc079c88aa22933071 Mon Sep 17 00:00:00 2001
From: "Fredrik Liljegren (Claude Code Opus 5.5)"
Date: Tue, 10 Nov 2026 09:42:35 +0100
Subject: [PATCH 2/3] fix: a 401 counts as signed out, and a failed write never
reloads the page on its own
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Bwp5QefjsjMFeq6CK6cT6w
---
packages/ui/src/lib/request.ts | 7 ++++---
packages/ui/src/lib/sign-in.ts | 10 ++++++++--
packages/ui/tests/sign-in.test.tsx | 13 ++++++++++++-
3 files changed, 24 insertions(+), 6 deletions(-)
diff --git a/packages/ui/src/lib/request.ts b/packages/ui/src/lib/request.ts
index 4ef3bd31..67726a04 100644
--- a/packages/ui/src/lib/request.ts
+++ b/packages/ui/src/lib/request.ts
@@ -2,12 +2,13 @@ import { markSignedOut } from './sign-in';
/**
* The server never redirects these requests; a redirect is IAP sending an expired sign-in to Google, which
- * a fetch cannot follow.
+ * a fetch cannot follow. A 401 is diffity's own sign-in gone. A write that fails this way may have taken the
+ * reader's text with it, so the page must not reload on its own.
*/
export async function apiRequest(url: string, init?: RequestInit): Promise {
const res = await fetch(url, { ...init, redirect: 'manual' });
- if (res.type === 'opaqueredirect') {
- markSignedOut();
+ if (res.type === 'opaqueredirect' || res.status === 401) {
+ markSignedOut({ lostWrite: (init?.method ?? 'GET').toUpperCase() !== 'GET' });
throw new Error('Signed out');
}
return res;
diff --git a/packages/ui/src/lib/sign-in.ts b/packages/ui/src/lib/sign-in.ts
index ab386a4f..6290c72c 100644
--- a/packages/ui/src/lib/sign-in.ts
+++ b/packages/ui/src/lib/sign-in.ts
@@ -1,12 +1,14 @@
let signedOut = false;
let reloaded = false;
+let lostWrite = false;
const listeners = new Set<() => void>();
export function isSignedOut(): boolean {
return signedOut;
}
-export function markSignedOut(): void {
+export function markSignedOut(cause: { lostWrite?: boolean } = {}): void {
+ lostWrite ||= !!cause.lostWrite;
if (signedOut) {
return;
}
@@ -28,10 +30,12 @@ export interface PageState {
/** Something the reader typed that a reload would throw away. */
hasDraft: boolean;
editing: boolean;
+ /** A save failed on the expired sign-in; its text may live only in memory. */
+ lostWrite: boolean;
}
export function shouldAutoReload(state: PageState, alreadyReloaded: boolean): boolean {
- return !alreadyReloaded && state.visible && !state.hasDraft && !state.editing;
+ return !alreadyReloaded && !state.lostWrite && state.visible && !state.hasDraft && !state.editing;
}
const TEXT_INPUT_TYPES = new Set(['', 'text', 'search', 'email', 'url', 'tel', 'password', 'number']);
@@ -48,6 +52,7 @@ export function readPageState(doc: Document = document): PageState {
visible: doc.visibilityState === 'visible',
hasDraft: fields.some(field => field.value.trim() !== ''),
editing,
+ lostWrite,
};
}
@@ -67,5 +72,6 @@ export function reloadIfSafe(reload: () => void = () => window.location.reload()
export function resetSignInForTests(): void {
signedOut = false;
reloaded = false;
+ lostWrite = false;
listeners.clear();
}
diff --git a/packages/ui/tests/sign-in.test.tsx b/packages/ui/tests/sign-in.test.tsx
index 15df887c..c44a7d9c 100644
--- a/packages/ui/tests/sign-in.test.tsx
+++ b/packages/ui/tests/sign-in.test.tsx
@@ -14,7 +14,7 @@ afterEach(() => {
document.body.replaceChildren();
});
-const CLEAN = { visible: true, hasDraft: false, editing: false };
+const CLEAN = { visible: true, hasDraft: false, editing: false, lostWrite: false };
describe('the request helper', () => {
it('asks not to follow redirects and passes a normal response through', async () => {
@@ -39,6 +39,16 @@ describe('the request helper', () => {
await expect(apiRequest('/api/info')).rejects.toThrow('Signed out');
expect(isSignedOut()).toBe(true);
+ expect(readPageState().lostWrite).toBe(false);
+ });
+
+ it('marks the page signed out on a 401, and never reloads it on its own after a failed write', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('', { status: 401 })));
+
+ await expect(apiRequest('/api/threads/1', { method: 'PATCH' })).rejects.toThrow('Signed out');
+ expect(isSignedOut()).toBe(true);
+ expect(readPageState().lostWrite).toBe(true);
+ expect(reloadIfSafe(vi.fn())).toBe(false);
});
});
@@ -51,6 +61,7 @@ describe('reloading after the sign-in expired', () => {
expect(shouldAutoReload({ ...CLEAN, hasDraft: true }, false)).toBe(false);
expect(shouldAutoReload({ ...CLEAN, editing: true }, false)).toBe(false);
expect(shouldAutoReload({ ...CLEAN, visible: false }, false)).toBe(false);
+ expect(shouldAutoReload({ ...CLEAN, lostWrite: true }, false)).toBe(false);
});
it('reloads only once', () => {
From 0a654fe5acfb123bcc4605bf2441b77f8163872f Mon Sep 17 00:00:00 2001
From: "Fredrik Liljegren (Claude Code Opus 5.5)"
Date: Tue, 10 Nov 2026 09:49:52 +0100
Subject: [PATCH 3/3] fix: a write still under way also keeps the page from
reloading on its own
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Bwp5QefjsjMFeq6CK6cT6w
---
packages/ui/src/lib/request.ts | 26 ++++++++++++++++++--------
packages/ui/src/lib/sign-in.ts | 18 ++++++++++++++----
packages/ui/tests/sign-in.test.tsx | 22 ++++++++++++++++++----
3 files changed, 50 insertions(+), 16 deletions(-)
diff --git a/packages/ui/src/lib/request.ts b/packages/ui/src/lib/request.ts
index 67726a04..874ac62f 100644
--- a/packages/ui/src/lib/request.ts
+++ b/packages/ui/src/lib/request.ts
@@ -1,15 +1,25 @@
-import { markSignedOut } from './sign-in';
+import { markSignedOut, writeSettled, writeStarted } from './sign-in';
/**
* The server never redirects these requests; a redirect is IAP sending an expired sign-in to Google, which
- * a fetch cannot follow. A 401 is diffity's own sign-in gone. A write that fails this way may have taken the
- * reader's text with it, so the page must not reload on its own.
+ * a fetch cannot follow. A 401 is diffity's own sign-in gone. A write may hold the reader's only copy of their
+ * text, so while one is under way, or after one failed this way, the page must not reload on its own.
*/
export async function apiRequest(url: string, init?: RequestInit): Promise {
- const res = await fetch(url, { ...init, redirect: 'manual' });
- if (res.type === 'opaqueredirect' || res.status === 401) {
- markSignedOut({ lostWrite: (init?.method ?? 'GET').toUpperCase() !== 'GET' });
- throw new Error('Signed out');
+ const write = (init?.method ?? 'GET').toUpperCase() !== 'GET';
+ if (write) {
+ writeStarted();
+ }
+ try {
+ const res = await fetch(url, { ...init, redirect: 'manual' });
+ if (res.type === 'opaqueredirect' || res.status === 401) {
+ markSignedOut({ lostWrite: write });
+ throw new Error('Signed out');
+ }
+ return res;
+ } finally {
+ if (write) {
+ writeSettled();
+ }
}
- return res;
}
diff --git a/packages/ui/src/lib/sign-in.ts b/packages/ui/src/lib/sign-in.ts
index 6290c72c..4002bebf 100644
--- a/packages/ui/src/lib/sign-in.ts
+++ b/packages/ui/src/lib/sign-in.ts
@@ -1,6 +1,7 @@
let signedOut = false;
let reloaded = false;
let lostWrite = false;
+let writesInFlight = 0;
const listeners = new Set<() => void>();
export function isSignedOut(): boolean {
@@ -18,6 +19,14 @@ export function markSignedOut(cause: { lostWrite?: boolean } = {}): void {
}
}
+export function writeStarted(): void {
+ writesInFlight++;
+}
+
+export function writeSettled(): void {
+ writesInFlight--;
+}
+
export function subscribeSignedOut(listener: () => void): () => void {
listeners.add(listener);
return () => {
@@ -30,12 +39,12 @@ export interface PageState {
/** Something the reader typed that a reload would throw away. */
hasDraft: boolean;
editing: boolean;
- /** A save failed on the expired sign-in; its text may live only in memory. */
- lostWrite: boolean;
+ /** A save is under way, or failed on the expired sign-in; its text may live only in memory. */
+ unsavedWrite: boolean;
}
export function shouldAutoReload(state: PageState, alreadyReloaded: boolean): boolean {
- return !alreadyReloaded && !state.lostWrite && state.visible && !state.hasDraft && !state.editing;
+ return !alreadyReloaded && !state.unsavedWrite && state.visible && !state.hasDraft && !state.editing;
}
const TEXT_INPUT_TYPES = new Set(['', 'text', 'search', 'email', 'url', 'tel', 'password', 'number']);
@@ -52,7 +61,7 @@ export function readPageState(doc: Document = document): PageState {
visible: doc.visibilityState === 'visible',
hasDraft: fields.some(field => field.value.trim() !== ''),
editing,
- lostWrite,
+ unsavedWrite: lostWrite || writesInFlight > 0,
};
}
@@ -73,5 +82,6 @@ export function resetSignInForTests(): void {
signedOut = false;
reloaded = false;
lostWrite = false;
+ writesInFlight = 0;
listeners.clear();
}
diff --git a/packages/ui/tests/sign-in.test.tsx b/packages/ui/tests/sign-in.test.tsx
index c44a7d9c..f51a2bbe 100644
--- a/packages/ui/tests/sign-in.test.tsx
+++ b/packages/ui/tests/sign-in.test.tsx
@@ -14,7 +14,7 @@ afterEach(() => {
document.body.replaceChildren();
});
-const CLEAN = { visible: true, hasDraft: false, editing: false, lostWrite: false };
+const CLEAN = { visible: true, hasDraft: false, editing: false, unsavedWrite: false };
describe('the request helper', () => {
it('asks not to follow redirects and passes a normal response through', async () => {
@@ -39,7 +39,7 @@ describe('the request helper', () => {
await expect(apiRequest('/api/info')).rejects.toThrow('Signed out');
expect(isSignedOut()).toBe(true);
- expect(readPageState().lostWrite).toBe(false);
+ expect(readPageState().unsavedWrite).toBe(false);
});
it('marks the page signed out on a 401, and never reloads it on its own after a failed write', async () => {
@@ -47,9 +47,23 @@ describe('the request helper', () => {
await expect(apiRequest('/api/threads/1', { method: 'PATCH' })).rejects.toThrow('Signed out');
expect(isSignedOut()).toBe(true);
- expect(readPageState().lostWrite).toBe(true);
+ expect(readPageState().unsavedWrite).toBe(true);
expect(reloadIfSafe(vi.fn())).toBe(false);
});
+
+ it('does not reload on its own while a write is still under way', async () => {
+ let answer!: (res: Response) => void;
+ vi.stubGlobal('fetch', vi.fn().mockReturnValueOnce(new Promise(resolve => { answer = resolve; })));
+
+ const save = apiRequest('/api/threads/1', { method: 'PATCH' });
+ expect(readPageState().unsavedWrite).toBe(true);
+ markSignedOut();
+ expect(reloadIfSafe(vi.fn())).toBe(false);
+
+ answer(new Response('{}', { status: 200 }));
+ await save;
+ expect(readPageState().unsavedWrite).toBe(false);
+ });
});
describe('reloading after the sign-in expired', () => {
@@ -61,7 +75,7 @@ describe('reloading after the sign-in expired', () => {
expect(shouldAutoReload({ ...CLEAN, hasDraft: true }, false)).toBe(false);
expect(shouldAutoReload({ ...CLEAN, editing: true }, false)).toBe(false);
expect(shouldAutoReload({ ...CLEAN, visible: false }, false)).toBe(false);
- expect(shouldAutoReload({ ...CLEAN, lostWrite: true }, false)).toBe(false);
+ expect(shouldAutoReload({ ...CLEAN, unsavedWrite: true }, false)).toBe(false);
});
it('reloads only once', () => {