diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 406e3d79bd57d..2b3e9bfb96c14 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -1,5 +1,13 @@ import type { ResolvedKeybindingsConfig, ScopedThreadRef } from "@t3tools/contracts"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -122,9 +130,10 @@ async function renderShortcut() { stack.defer(() => { delete window.desktopBridge; }); - stack.use(await render()); + const screen = stack.use(await render()); const environment = stack.move(); return { + router: screen.router!, /** Attaches an element to the document until the test ends. */ append(element: HTMLElement) { document.body.append(element); @@ -148,6 +157,43 @@ function press(target: Element = document.body) { } describe("root reopen shortcut", () => { + it.each([ + { action: "switch routes", goBack: false, expectedPath: "/newer" }, + { action: "leave and return", goBack: true, expectedPath: "/" }, + ])( + "restores both queued views without navigating when you $action during the reopen", + async ({ goBack, expectedPath }) => { + setup(); + const store = useClosedViewStore.getState(); + store.remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const result = Promise.withResolvers>(); + state.openPreview.mockReturnValue(result.promise); + await using view = await renderShortcut(); + const { history } = view.router; + state.navigate.mockImplementation(async () => { + history.push("/restored-owner"); + }); + + await act(() => { + press(); + menuAction?.("view.reopenClosed"); + }); + await act(() => { + history.push("/newer"); + if (goBack) history.back(); + }); + await act(() => result.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref); + expect(panel.surfaces.map((surface) => surface.id)).toEqual( + expect.arrayContaining(["browser:new-tab", "diff"]), + ); + expect(history.location.pathname).toBe(expectedPath); + }, + ); + it("serializes deliberate presses while a browser restore waits for RPC", async () => { setup(); useClosedViewStore @@ -174,6 +220,53 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }); + it("follows both queued restores from a page with an allowing navigation blocker", async () => { + setup(); + const olderRef = { ...ref, threadId: "thread-2" } as ScopedThreadRef; + const store = useClosedViewStore.getState(); + store.remember({ + kind: "panel-tab", + threadRef: olderRef, + surface: { kind: "diff", id: "diff" }, + }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const opened = Promise.withResolvers>(); + state.openPreview.mockReturnValue(opened.promise); + + const history = createMemoryHistory({ initialEntries: ["/welcome"] }); + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }); + const router = createRouter({ + history, + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: "welcome" }), + createRoute({ getParentRoute: () => root, path: "$environmentId/$threadId" }), + ]), + }); + state.navigate.mockImplementation(router.navigate); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + // The test supplies its own routes and history. + await using _view = await render(, { router: false }); + using _blocker = { + [Symbol.dispose]: history.block({ blockerFn: () => false, enableBeforeUnload: false }), + }; + + await act(() => { + press(); + press(); + }); + await act(() => opened.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + expect(history.location.pathname).toBe("/remote/thread-2"); + }); + it("does not create a second browser when navigation fails after restoring it", async () => { setup(); const store = useClosedViewStore.getState(); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 551dbc98d8abc..1bc9d62a20c8e 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -7,7 +7,7 @@ import { scopeThreadRef, } from "@t3tools/client-runtime/environment"; import type { ScopedThreadRef } from "@t3tools/contracts"; -import { useNavigate, useParams } from "@tanstack/react-router"; +import { linkOptions, useNavigate, useParams, useRouter } from "@tanstack/react-router"; import { useGT } from "gt-react"; import { useEffect, useEffectEvent, useRef } from "react"; @@ -49,6 +49,12 @@ import { import { toastManager } from "./ui/toast"; import { readIssueListPreferences } from "./issue/issueListPreferences"; +declare module "@tanstack/react-router" { + interface HistoryState { + reopenedViewId?: string; + } +} + const PREVIEW_FORWARDED_COMMANDS = [ "workspace.focusNext", "workspace.focusPrevious", @@ -72,6 +78,7 @@ const isGlobalIssues = (ref: ScopedThreadRef) => export function ReopenClosedViewShortcut() { const gt = useGT(); const navigate = useNavigate(); + const router = useRouter(); const params = useParams({ strict: false }); const target = resolveThreadRouteTarget(params); const draft = useComposerDraftStore((state) => @@ -94,8 +101,10 @@ export function ReopenClosedViewShortcut() { const hasHistory = useClosedViewStore((state) => state.entries.length > 0); const openPreview = useAtomCommand(previewEnvironment.open); const pending = useRef(Promise.resolve()); + type ReopenNavigation = { location: typeof router.history.location }; + const reopenNavigation = useRef(null); - const reopenNext = useEffectEvent(async () => { + const reopenNext = useEffectEvent(async (request: ReopenNavigation) => { const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom); const drafts = useComposerDraftStore.getState(); const panelsByThread = useRightPanelStore.getState().byThreadKey; @@ -142,28 +151,59 @@ export function ReopenClosedViewShortcut() { return; } useClosedViewStore.getState().remove(restore.id); + if (router.history.location !== request.location) return; + + let destination; if (globalPullRequests) { const selected = selectSelectedRightPanelSurface( useRightPanelStore.getState().byThreadKey, ref, ); - await navigate({ + destination = linkOptions({ to: "/pull-requests", search: (previous) => pullRequestsSearchForRestore(previous, selected), }); } else if (globalIssues) { - await navigate({ to: "/issues", search: readIssueListPreferences() }); + destination = linkOptions({ to: "/issues", search: readIssueListPreferences() }); } else { const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null; - if (draftId !== null) - await navigate({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }); - else await navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + destination = + draftId !== null + ? linkOptions({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }) + : linkOptions({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + } + + const { history } = router; + if (router.buildLocation(destination).publicHref === history.location.href) { + const { reopenedViewId } = history.location.state; + await navigate({ ...destination, state: reopenedViewId ? { reopenedViewId } : {} }); + return; + } + + // An allowing blocker can defer the commit. Only the reopen's first history hop extends the queue. + const unsubscribe = history.subscribe(({ location, action }) => { + if (location === request.location) return; + unsubscribe(); + if (action.type === "PUSH" && location.state.reopenedViewId === restore.id) { + request.location = location; + } + }); + try { + await navigate({ ...destination, state: { reopenedViewId: restore.id } }); + } catch (error) { + unsubscribe(); + throw error; } + unsubscribe(); }); const enqueueReopen = useEffectEvent(() => { + const location = router.history.location; + const previous = reopenNavigation.current; + const request = previous?.location === location ? previous : { location }; + reopenNavigation.current = request; pending.current = pending.current - .then(() => reopenNext()) + .then(() => reopenNext(request)) .catch((error: unknown) => { toastManager.add({ type: "error", diff --git a/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts new file mode 100644 index 0000000000000..d1270ef325df4 --- /dev/null +++ b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts @@ -0,0 +1,103 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +interface ReopenGate { + readonly closed: Promise; + readonly requested: Promise; + readonly arm: () => void; + readonly release: () => Promise; +} + +declare global { + interface Window { + reopenGate: ReopenGate; + } +} + +test( + "A browser tab finishing its reopen leaves the newer conversation on screen", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const owner = await t3.thread({ project, title: "Browser owner", messages: ["first"] }); + await t3.thread({ + project, + title: "Newer conversation", + messages: ["Stay in this conversation"], + }); + + await browser.addInitScript(() => { + const closed = Promise.withResolvers(); + const requested = Promise.withResolvers(); + const restored = Promise.withResolvers(); + let hasClosedBrowser = false; + let armed = false; + let sendHeld = () => {}; + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key, value) { + setItem.call(this, key, value); + if (key !== "t3code:closed-views:v2") return; + const hasBrowser = value.includes('"kind":"browser"'); + if (hasBrowser) closed.resolve(); + else if (hasClosedBrowser) restored.resolve(); + hasClosedBrowser = hasBrowser; + }; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (!armed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = [parsed].flat(); + const isOpen = (message: { _tag?: string; tag?: string }) => + message._tag === "Request" && message.tag === "preview.open"; + const previewOpens = messages.filter(isOpen); + if (previewOpens.length === 0) return send.call(this, data); + armed = false; + const others = messages.filter((message) => !isOpen(message)); + if (others.length > 0) send.call(this, JSON.stringify(others)); + sendHeld = () => + send.call(this, Array.isArray(parsed) ? JSON.stringify(previewOpens) : data); + requested.resolve(); + }; + window.reopenGate = { + closed: closed.promise, + requested: requested.promise, + arm: () => { + armed = true; + }, + release: () => { + sendHeld(); + return restored.promise; + }, + }; + }); + + await t3.open(owner); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByRole("button", "Close Browser", { exact: true }).tap(); + await browser.evaluate(async () => { + await window.reopenGate.closed; + window.reopenGate.arm(); + return null; + }); + + await browser.keyboard.press("Control+Shift+t"); + await browser.evaluate(async () => { + await window.reopenGate.requested; + return null; + }); + await screen.getByRole("button", "Newer conversation", { exact: false }).tap(); + const newerMessage = screen.getByText("Stay in this conversation", { exact: true }); + await newerMessage.waitFor(); + const newerUrl = await browser.url(); + await browser.evaluate(async () => { + await window.reopenGate.release(); + return null; + }); + + await app.screenshot("conversation-after-browser-reopens"); + await expect(browser).toHaveURL(newerUrl); + }, +);