Skip to content

fix(site/src): let swipe-back reach the chat list from a notification - #31299

Merged
mafredri merged 13 commits into
mainfrom
mafredri/agents-ios-swipe-back
Nov 12, 2026
Merged

mafredri merged 13 commits into
mainfrom
mafredri/agents-ios-swipe-back

Conversation

@mafredri

@mafredri mafredri commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

On iOS, a chat opened from a push notification in the installed Agents app could not be swiped back to the chat list. The service worker answered the click with clients.openWindow(), which iOS shows as a second window over a blank about:blank one. That window starts on the chat as its only history entry, so the edge swipe had nothing to go back to, and a back swipe that lands on its first entry closes it within about half a second, leaving the blank window with Safari's toolbar until the app is force-closed.

The push handler now gives notifications a Declarative Web Push navigate URL (NotificationOptions.idl). Safari opens that URL itself instead of firing notificationclick (WKWebsiteDataStore.mm), and the installed app loads it in its own window. With the app in the background, the tap now loads the chat in the running app. Browsers without Declarative Web Push ignore the member, as Chromium did in a local check, and keep using the notificationclick handler.

When Safari opens the app on a chat for a notification, as the window's only entry, that entry becomes the chat list, and the chat is pushed on top once the list has painted (notificationWindow.ts), so the swipe returns to the list. The service worker marks the navigate URL with ?notification=1 so the page can tell these windows apart, and the page removes the marker. Windows from clients.openWindow() keep their single entry, as on main: iOS closes such a window when a swipe reaches its first entry, so a list there turns the swipe into the blank screen. Those windows still occur on iOS before 18.4, which has no Declarative Web Push, and for notifications that the previous service worker showed. When the server rendered the page for a signed-out visitor, the window is left alone so the sign-in redirect keeps the chat. The list replaces the first entry instead of being pushed because WebKit's back swipe skips entries pushed without user activation down to the first entry (itemStartingAtIndexSkippingItemsAddedByJSWithoutUserGesture). isStandaloneDisplayMode() moves from chatAttachments.ts to utils/platform.ts for the second caller.

Verified on an iPhone (Safari 27.0.1) against an ephemeral deployment of this branch, with real push notifications: from a force-closed app and from the app in the background, the tap opened the chat, the swipe went back to the list, and the app kept working. That run predates the ?notification=1 marker, which only unit tests cover. Testing on a frontend-mode ephemeral deployment needs the branch's worker: its proxy serves dogfood's /serviceWorker.js, so a notification tap there takes the clients.openWindow() path and stays on main's behavior. Not verified: Safari on macOS also handles navigate itself, so where the service worker used to reuse an open Agents tab, Safari may open a new one.

Fixes CODAGT-1474

Decision log

The device runs used a temporary diagnostics build (not in this PR) that recorded history and page lifecycle events to storage that survives a force-close, plus test notifications that opened the app in each variant.

Variant Result on the iPhone
openWindow() of the chat, chat list made the first entry (this PR's first version) The swipe reached the list, then iOS closed the window: stuck
Same, plus pushing the list again when a back step lands on the first entry The app pushed 4 ms after popstate; iOS still closed the window about 570 ms later
openWindow('/agents'), the manifest start_url, with the chat handed over through Cache Storage or ?chat= Same closing window, also when the user tapped into the chat
Notification navigate URL Chat opened in the app's own window; swipes to the first entry stayed in the app. With the app in the background, the tap loaded the chat in the running window
  • clients.openWindow() hands the host app the choice of web view (WebsiteDataStore::openWindowFromServiceWorker only checks that the returned view is loading). The host is closed source, which is why the variants were measured instead of read.
  • Rejected: the chat list first in every standalone window that starts on a chat. A frontend-mode ephemeral deployment, which runs dogfood's worker, showed the first table row again: the swipe reached the list, then iOS closed the window and left the blank screen.
  • Rejected: coderd sending Declarative Web Push JSON (web_push: 8030). The service worker shows every notification, and the navigate member gives the same click handling without a server change.
  • Rejected: limiting navigate to iOS by user agent. iPadOS reports a Mac user agent, and Safari on macOS handles navigate by design.

Not changed: the chat top bar's mobile Back arrow pushes /agents instead of going back, so swiping back from that list returns to the chat. main does the same.

WebKit back-swipe probe

iOS picks the swipe target with goBackItemSkippingItemsWithoutUserGesture() (ViewGestureController::itemForSwipeDirection), and so does WebKitGTK's toolbar back button (WebPageProxy::goBack). Playwright's page.goBack() and history.back() do not, so this probe clicks the MiniBrowser toolbar with xdotool. In Playwright WebKit 26.6, scenario D goes back to /a (the skipping is active), C to /list, and E to its first entry, /chat.

// Probes the WebKit back-forward rules that decide where iOS swipe-back goes.
//
// iOS swipe-back picks its target with
// WebBackForwardList::goBackItemSkippingItemsWithoutUserGesture()
// (ViewGestureController::itemForSwipeDirection). That function skips
// history items that JavaScript added without user interaction. Playwright's
// page.goBack() and JS history.back() do not use it, so this probe clicks the
// MiniBrowser toolbar back button instead: webkit_web_view_go_back() ->
// WebPageProxy::goBack() -> goBackItemSkippingItemsWithoutUserGesture().
//
// Run under Xvfb: xvfb-run -a node probe.mjs
import { execSync } from "node:child_process";
import { createRequire } from "node:module";

const require = createRequire(`${process.env.SITE_DIR}/package.json`);
const { webkit } = require("@playwright/test");

const origin = "http://probe.test";
const pageHTML = (boot) => `<!doctype html><html><head>
<meta name="viewport" content="width=device-width, initial-scale=1"></head><body>
<a id="link" href="/chat" style="display:block;padding:40px;font-size:24px">open chat</a>
<script>
document.getElementById("link").addEventListener("click", (e) => {
	e.preventDefault();
	history.pushState(null, "", "/chat");
});
${boot}
</script></body></html>`;

// Clicks MiniBrowser's toolbar back button (located with findback.mjs).
function uiBack() {
	const win = execSync(
		"xdotool search --onlyvisible --name '.*' | tail -2 | head -1",
	)
		.toString()
		.trim();
	execSync(`xdotool mousemove --window ${win} 20 18 click 1`);
}

async function scenario(browser, name, { path, boot = "", tap = false }) {
	const context = await browser.newContext({
		viewport: { width: 400, height: 700 },
		hasTouch: true,
	});
	const page = await context.newPage();
	await page.route(`${origin}/**`, (route) =>
		route.fulfill({ contentType: "text/html", body: pageHTML(boot) }),
	);
	// Replace the initial about:blank entry so the window starts with one
	// history entry, like a window opened by clients.openWindow().
	await page.evaluate((url) => location.replace(url), `${origin}${path}`);
	await page.waitForURL(`${origin}/**`);
	if (tap) {
		await page.tap("#link");
	}
	await page.waitForTimeout(300);
	const before = new URL(page.url()).pathname;
	const length = await page.evaluate(() => history.length);
	uiBack();
	await page.waitForTimeout(1000);
	const after = new URL(page.url()).pathname;
	console.log(
		`${name}\n  on ${before}, history.length=${length}, UI back -> ${after}${
			after === before ? " (did not move)" : ""
		}`,
	);
	await context.close();
}

const browser = await webkit.launch({ headless: false });
console.log(`WebKit ${browser.version()}`);
await scenario(browser, "A: window opened at /chat", { path: "/chat" });
await scenario(browser, "B: window opened at /list, user taps -> /chat", {
	path: "/list",
	tap: true,
});
await scenario(
	browser,
	"C: window opened at /chat, boot script replaceState(/list) + pushState(/chat), no user gesture",
	{
		path: "/chat",
		boot: `history.replaceState(null, "", "/list"); history.pushState(null, "", "/chat");`,
	},
);
await scenario(
	browser,
	"D: control, window opened at /a, boot script pushState(/b) + pushState(/c), no user gesture",
	{
		path: "/a",
		boot: `history.pushState(null, "", "/b"); history.pushState(null, "", "/c");`,
	},
);
await scenario(
	browser,
	"E: rejected design, window opened at /chat, boot script pushState(/list) + pushState(/chat), no user gesture",
	{
		path: "/chat",
		boot: `history.pushState(null, "", "/list"); history.pushState(null, "", "/chat");`,
	},
);
await browser.close();

🤖 This PR was created with the help of Coder Agents, and will be reviewed by a human. 🏂🏻

@mafredri

This comment has been minimized.

@coder-agents-review

coder-agents-review Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Review posted | View chat
Requested: 2026-10-26 21:06 UTC by @mafredri

Review history
  • R1 (2026-10-26): 10 reviewers, 1 Nit, 2 P3, 2 P4, COMMENT. Review

deep-review v0.13.0 | Round 1 | e17851d..38cc870

Last posted: Round 1, 5 findings (2 P3, 2 P4, 1 Nit), COMMENT. Review

Finding inventory

Finding inventory: PR #31299

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P4 Open chatListHistoryEntry.test.ts:57 Test does not pin { idx: 0 } on the list entry; null state passes, and PR description claims otherwise R1 Netero, Bisky, Leorio Yes
CRF-2 Note Note (body) chatListHistoryEntry.ts:25 Entry states hand-copy React Router's private history state shape (createKey format, no masked) R1 Netero, Razor No
CRF-3 P3 Open chatListHistoryEntry.ts:4 Doc comment names the wrong actor, omits no-op conditions and the run-before-router requirement R1 Gon P2, Leorio P4 Yes
CRF-4 P3 Open chatListHistoryEntry.ts:22 Comment does not say what breaks if the states are null (useBlocker) R1 Gon P3, Leorio P4 Yes
CRF-5 P4 Open chatListHistoryEntry.ts:20 WebKit skip rule cited without the WebKit function name R1 Leorio Yes
CRF-6 Nit Open chatListHistoryEntry.ts:16 chat holds a PathMatch; rename to chatMatch R1 Gon Yes
CRF-7 P2 Dropped by orchestrator (comment says what navigator.standalone means, which the type does not) platform.ts:21 Doc comment restates function name and IOSNavigator type R1 Gon No
CRF-8 P2 Dropped by orchestrator (first clause gives the reason; the list documents what the helper fakes) chatListHistoryEntry.test.ts:7 Test helper comment lists the lines below it R1 Gon No
CRF-9 Note Dropped by orchestrator (verification note, no action) chatListHistoryEntry.ts:24 Back target renders the same view as the in-app path R1 Nami No
CRF-10 Note Dropped by orchestrator (verification note, no action) chatListHistoryEntry.test.ts:32 Each guard has a test row that fails when removed R1 Bisky No
CRF-11 Note Dropped by orchestrator (verification note, no action) commit messages Commit messages follow conventions R1 Leorio No

Contested and acknowledged

Round log

Round 1

Netero: 1 P4, 1 Note. No P0, proceed to panel.

Full panel (round 1). Specialists: ging-ts (.ts), ging-react (.tsx), nami (frontend), melody (history.state crosses into React Router's format). Core: pariston, mafuuu. Pool: bisky (tests), gon and leorio (once-per-PR floor). Wildcard: razor (random). 10 reviewers, above the 6 to 8 focused target because of the 4 required specialists plus the Gon and Leorio floor.

Cross-check: CRF-3 settled at P3 (Gon P2 rested partly on the rationale sentence being a restatement; it is the why. The run-before-router requirement is stated at the only call site, router.tsx:568. Keep-argument: an exported function's doc omits a precondition whose violation desyncs the router index). CRF-4 at P3 (higher of Gon P3, Leorio P4). Leorio's PR-description P4 merged into CRF-1 (same fix). Leorio's WebKit-function Note asks for a change, posted as CRF-5 P4. CRF-7 keep-argument: restating comments in a shared util cost every reader; dropped because the second sentence carries information the type does not. CRF-8 keep-argument: restating lines drift when the helper changes; dropped because the rewrite loses the explanation of the URL and display-mode fakes. No useBlocker on chat routes today (useUnsavedChangesPrompt callers are settings forms), so CRF-1 consequence is latent; kept at P4. Pariston: iOS device not tested (PR states it); if iOS opens start_url first, the change is a no-op. Reviewed against e17851d..38cc870.

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T14:27:10.549879Z 87b44de Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

This comment has been minimized.

coder-agents-review[bot]

This comment was marked as outdated.

@coder

This comment was marked as outdated.

@mafredri
mafredri force-pushed the mafredri/agents-ios-swipe-back branch 2 times, most recently from 0e360d6 to 87b44de Compare October 27, 2026 14:21
@linear-code

linear-code Bot commented Oct 27, 2026

Copy link
Copy Markdown

CODAGT-1474

@mafredri

This comment has been minimized.

@mafredri
mafredri marked this pull request as ready for review October 27, 2026 14:24
@mafredri
mafredri requested a review from a team as a code owner October 27, 2026 14:24
@pr-queue-manager
pr-queue-manager Bot requested a review from jaaydenh October 27, 2026 14:25
@chatgpt-codex-connector

This comment has been minimized.

@mafredri

Copy link
Copy Markdown
Member Author

Note to self, squash commit message:

On iOS, the service worker answered a notification click with
clients.openWindow(), which the installed app shows as a second window
over a blank one. A back swipe to that window's first page closed it and
left the blank window on screen until the app was force-closed.

Notifications now carry a Declarative Web Push navigate URL, so Safari
opens the chat in the app's own window, including when the app is
already running. A standalone window that starts on a chat gets the chat
list as its first entry, with the chat pushed on top once the list has
painted, so the swipe returns to the list.

Fixes CODAGT-1474

A push notification click opens the chat as the only history entry of
the installed app window. There is no browser back button there, so the
iOS edge swipe had nothing to go back to, while a chat opened from the
chat list could swipe back to it.

When a standalone window starts on a chat with no other entry, the
first entry becomes the chat list and the chat is pushed on top. WebKit's
back swipe skips entries that JavaScript pushes without user interaction
but stops at the window's first entry, so pushing the list as well would
leave the swipe on the same chat.
The chat list history entry needs the same "running as an installed
app" check that the iOS attachment share sheet already had, so both
now use one definition in utils/platform.
On iOS, a notification click opens the chat in a window stacked on a
blank about:blank window. A back swipe that leaves that window on its
first history entry closes it, which leaves only the blank page with no
way back (CODAGT-1474). A device capture showed this for every swipe
that landed on the first entry, on main too, and never for other
entries.

The window now starts on the chat list and opens the chat once the
list has painted, so the swipe shows the list instead of a blank page.
When a back step lands on the first entry, the same location is pushed
again so the window always has a back entry.
Device testing showed that pushing the chat list again when a back step
lands on a notification window's first entry does not keep iOS from
closing the window, so drop that guard.

A notification click can now also launch the chat list with the chat in
the query (/agents?chat=<id>), or name the chat after boot through
requestNotificationChat. Either way the chat opens on top of the list
once the list has painted, the same as for a chat launched directly.
On iOS, a notification click that the service worker answers with
clients.openWindow() opens the installed app in a second window over a
blank one. A back swipe to that window's first page closes it and
leaves the blank one on screen until the app is force-closed.

Give notifications a Declarative Web Push navigate URL. Safari then
opens the URL itself without notificationclick, and the installed app
loads it in its own window, including when it is already running.
Browsers without Declarative Web Push ignore the member and keep using
the notificationclick handler.
Device testing showed that clients.openWindow() opens the installed iOS
app in the closing second window for the start URL too, with or without
the chat in the query, so nothing launches the chat list with a chat to
open. Remove the ?chat= handoff and requestNotificationChat. The
Declarative Web Push launch opens the chat URL directly, which
openChatListFirst handles.
Name the WebKit rule that makes pushing the chat list as well land the
back swipe on the chat, so a reader can check it without the PR.
With an expired session, the router sends a notification-opened chat to
sign in with the current location as the redirect. openChatListFirst had
already replaced that location with the chat list, so signing in landed
on the list instead of the chat. Skip the rewrite when the server
rendered the page without a signed-in user.
@mafredri
mafredri force-pushed the mafredri/agents-ios-swipe-back branch from 87b44de to 24b950f Compare November 4, 2026 10:04
…ndows

A device test on an ephemeral deployment, whose proxy serves the
deployed service worker, showed the chat list entry turning the back
swipe into a blank screen. Without a navigate URL the click goes through
clients.openWindow(), and iOS closes that window when a swipe reaches its
first entry. The same happens on iOS before 18.4, which lacks Declarative
Web Push, and for notifications the previous service worker showed.

The service worker now marks the navigate URL with a notification query
parameter, and openChatListFirst only rewrites marked windows and removes
the marker. Windows opened with clients.openWindow() keep their single
entry, as on main.
@mafredri
mafredri force-pushed the mafredri/agents-ios-swipe-back branch from e01f44b to da10389 Compare November 5, 2026 12:41
*/
export const notificationLaunchParam = "notification";

let pendingChatPath: string | null = null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion (non-blocking): keep the pending chat in the URL instead of module state.

pendingChatPath is mutable state that lives outside both React and the router. The comment above hasPendingChatPath is a symptom of that: the React Compiler assumes module-level values don't change, so the hook needs accessor functions to read the variable fresh. It also means a reload during the paint wait drops the chat, because the first entry is then plain /agents.

The router already tracks the URL, so the pending chat can live there.

1. openChatListFirst(): write the agent ID into a query parameter on the first entry instead of setting pendingChatPath:

const pendingChatParam = "notification-chat";

// replaces the last two lines of openChatListFirst()
url.searchParams.set(pendingChatParam, chatMatch.params.agentId);
window.history.replaceState(null, "", `/agents${url.search}${url.hash}`);

2. useOpenNotificationChat(): read the parameter from the router location. Once the list has painted, replace the entry to drop the parameter, then push the chat:

export function useOpenNotificationChat(isListLoading: boolean): void {
	const navigate = useNavigate();
	const { search, hash } = useLocation();
	const searchParams = new URLSearchParams(search);
	const agentId = searchParams.get(pendingChatParam);
	searchParams.delete(pendingChatParam);
	const listSearch = searchParams.size > 0 ? `?${searchParams}` : "";

	useEffect(() => {
		if (!agentId) {
			return;
		}
		let frame = 0;
		const open = () => {
			frame = requestAnimationFrame(() => {
				frame = requestAnimationFrame(async () => {
					await navigate(`/agents${listSearch}`, { replace: true });
					await navigate(`/agents/${agentId}${listSearch}${hash}`);
				});
			});
		};
		const timer = isListLoading ? setTimeout(open, 1500) : undefined;
		if (!isListLoading) {
			open();
		}
		return () => {
			clearTimeout(timer);
			cancelAnimationFrame(frame);
		};
	}, [agentId, listSearch, hash, isListLoading, navigate]);
}

Notes:

  • Await the replace before the push. Two back-to-back navigate() calls on a data router can interrupt each other. If the replace is dropped, /agents?notification-chat=... stays under the chat, and swiping back to it opens the chat again.
  • The replace goes through history.replaceState, just like the current pre-router rewrite, so WebKit still treats the first entry as browser-created and the back swipe can reach it.
  • The window.location.pathname === "/agents" check is no longer needed. If the user opens another chat before the timer fires, the parameter leaves the URL, agentId becomes null, and the effect cleanup cancels the pending frame or timer.
  • After a reload, notificationLaunchParam is already gone, so openChatListFirst() returns early and the hook still opens the chat from the parameter.
  • The cost is a query parameter that's briefly visible on the list URL, and the hash sits on the list entry until the replace runs. The signed-out path is unchanged.
  • notificationWindow.test.tsx would need its intermediate expectations updated: after openChatListFirst() the search includes notification-chat, and the final history should be one replace followed by one push.

@mafredri mafredri Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd keep the module variable. The pending chat should open once, for the launch that set it. A module variable lasts exactly one page load. A URL parameter stays in the window's first history entry, and the hook acts on it again whenever that entry comes back.

I ran your hook next to the current one in jsdom, with the router setup from notificationWindow.test.tsx. In both runs I open Settings while the list is still loading:

  • Back from Settings: the current hook stays on /agents. Yours pops to /agents?notification-chat=<id>, replaces it with /agents and pushes the chat, so the notification chat opens a second time.
  • The Settings back button: it links to the from state that the Settings button saved, /agents?notification-chat=<id>. The current hook stays on /agents. Yours pushes that URL, replaces it and pushes the chat, so the chat opens a second time here too.

It also makes /agents?notification-chat=<id> open the chat from any link. A browser tab on that URL ends on the chat with your hook and on /agents with the current one. Today only a notification launch sets this up: openChatListFirst requires the launch marker, standalone display, a single history entry and a signed-in visitor.

You're right that a reload during the wait drops the chat. The wait ends when the list loads, or at most 1.5 s after the layout mounts. After the reload the window shows the chat list, the screen the back swipe leads to. The accessor functions are what this costs, and that's cheaper than opening the chat twice.

🤖 Posted using /amend-review skill via Coder Agents.

@mafredri
mafredri merged commit 158fd06 into main Nov 12, 2026
32 of 34 checks passed
@mafredri
mafredri deleted the mafredri/agents-ios-swipe-back branch November 12, 2026 14:01
@mafredri
mafredri temporarily deployed to main November 12, 2026 14:01 — with GitHub Actions Inactive
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 12, 2026

This branch was previously deployed

1 inactive deployment
main — e01f44ba Deployed Nov 12, 2026 by mafredri via cla #254954
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants