From f657900b56d5b3694d2860a15bd915f7fbd90a0f Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Tue, 24 Nov 2026 11:36:49 +0000 Subject: [PATCH] feat(web): step Back through open work-area tabs in narrow mode In a window 980 px wide or less, a user's tab open or switch pushes a same-URL history entry, and a session-storage map keyed by the entry's key records the thread and tab it shows. Back shows the previous open tab, skips closed tabs, and leaves the thread after the starting tab. One history listener per browser history, installed with the router, makes the skips that must not depend on the shown thread: wide windows step as if the tab entries were not there, and entries of deleted threads (and their side chats) are skipped. Entries the app adds itself are tagged when reached, a quote link keeps its own reveal, closing Settings or Usage keeps Forward free of the modal, and Reopen Closed View and the delete fallback treat our tab steps as no navigation. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../components/ReopenClosedViewShortcut.tsx | 4 +- .../src/components/sidebar/mainAppLocation.ts | 2 + apps/web/src/fork/workArea/WorkArea.tsx | 2 + .../fork/workArea/tabHistory.browser.test.tsx | 966 ++++++++++++++ .../fork/workArea/tabHistory.logic.test.ts | 1109 +++++++++++++++++ .../web/src/fork/workArea/tabHistory.logic.ts | 193 +++ apps/web/src/fork/workArea/tabHistory.ts | 354 ++++++ apps/web/src/fork/workArea/tabHistoryTags.ts | 82 ++ apps/web/src/hooks/useThreadActions.ts | 11 +- apps/web/src/router.ts | 5 +- 11 files changed, 2724 insertions(+), 6 deletions(-) create mode 100644 apps/web/src/fork/workArea/tabHistory.browser.test.tsx create mode 100644 apps/web/src/fork/workArea/tabHistory.logic.test.ts create mode 100644 apps/web/src/fork/workArea/tabHistory.logic.ts create mode 100644 apps/web/src/fork/workArea/tabHistory.ts create mode 100644 apps/web/src/fork/workArea/tabHistoryTags.ts diff --git a/README.md b/README.md index 8ffafdeba06c9..78863ce5261b7 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ This is a fork of T3 Code that integrates a few additional features, including: - While the agent works, Chat mode shows "Working for" and the time just above the message box, in the sub-thread where you last wrote to it in that run, or else in the main list. - "Enable Dashboard", beside Display mode in the same menu, gives the thread a Dashboard in either mode: a Dashboard tab in the right panel (+ → Dashboard) with six status slots that the agent writes with its `dashboard_set` tool and reads with `dashboard_get`. Each slot shows how long ago it changed, and new text stays highlighted until you click the slot. Select text in a slot to quote it with Cite, as you would in a message. Agents can link to the Dashboard in their messages, and a click on the link opens it. - Settings → Threads → New threads → Display mode picks the mode for threads you start from the message box in the web or desktop app. Threads that agents, scheduled tasks, side chats or the mobile app start open in Normal mode, and existing threads keep their mode. -- **The work area:** everything right of the thread list is one area of panes, starting as one pane with a Chat tab for the selected thread. Drag a tab onto a pane's tab strip to move it there, onto an edge of a pane's content to split that side, or onto the middle to join that pane. The tab menu also has Split right and Split down. When there is one pane, a Split right button at the right end of the tab bar splits it and opens a New tab page. Panes split again in either direction. Drag the divider between two panes, or use the arrow keys on it, to resize. Double-click the divider to reset its size. Closing a pane's last tab closes the pane. Any pane with a message box (a Chat tab, a reply tab, or a side-thread tab) stays at least 360 px wide. Drag a same-project thread from the thread list into the area to open its chat as another Chat tab. File links in that chat open that thread's file as a tab beside it. You cannot drop another project's thread into the area, though dropping it on a message box still adds it as context. A thread link, chip, or header breadcrumb in a chat opens a same-project thread as a Chat tab beside the chat, and opens a thread of another project or environment on its own page. Subagents and side chats open as side-thread tabs beside the chat, as in upstream T3 Code. A Cmd or Ctrl click, a middle click, or "Open in main view" opens them on their own page. Reply, "N replies" on a message, or a sub-thread in the Replies list opens that sub-thread as its own tab. Opening one from the Replies list places it next to the list. Each thread keeps its own layout. The last Chat tab cannot close. Closing the selected thread's Chat removes it until + → Chat brings it back. Files, links, and diffs that open by themselves go beside the chat, never over it. A window 980 px wide or less shows every tab in one strip and keeps the panes for when there is room. The right panel's show, hide, and maximize controls are gone. A press anywhere on a tab switches to it at once. No tab is ever hidden except a browser or device tab playing in the floating mini player, a small floating window over the chat. "Preview: Toggle", picture-in-picture, and a device's Float move the tab into the mini player and keep the session. Closing the mini player, choosing "Open in panel", or using "Preview: Toggle" again puts the tab back in its pane. If the window or layout stops showing the Chat that holds the mini player, the tab goes back to its pane and the mini player closes. "Preview: Toggle" on an empty browser tab (a New tab page with no page loaded) closes that tab. "Diff: Toggle" closes the Diff tab when it is shown and opens it when it is not. Reopen Closed View can bring back a closed Diff tab. There is no terminal drawer under the Chat. Every terminal is a terminal tab in a pane. Project scripts and the Run button on a chat code block run in an idle terminal tab, or open a new terminal tab. A terminal that the server already runs for the thread (such as a worktree setup shell) shows as a background tab. "Terminal: Toggle" (Cmd+J or Ctrl+J) is gone, including from Settings → Keybindings. Split, new, and close terminal shortcuts act on the focused terminal tab. Drag a file from the Files tree, or a link from a chat message, onto a pane to open it there. Supported chat links are file, pull request, issue, thread, `board://`, Dashboard, and web links. Drop the item on a tab strip to open it at that spot, on one of a pane's four edges to split that side, or on the middle to add it to that pane. If the item is already open in another pane, the drop moves its tab there. If you press a key or click before a slow drop finishes opening, the item opens where a click would instead. A dropped file keeps a standalone Files tab open beside it. A plain click on a file still replaces the Files tab. A full pull request or issue URL opens as a pull request or issue tab when a click opens that kind of tab. Other web links, and pull request or issue links that do not open that kind of tab, drag whenever the preview browser is available. A drop opens those links in the preview browser even when a click opens them in the system browser. Without a preview browser, those links do not drag. Folder rows in the Files tree, short references like `#42`, commit links, and web image and video URLs do not drag. A chat file link drags whenever a click opens it in the work area. A dropped file link opens what its click opens, in the pane you chose, so it can open a workspace folder or a workspace image or video file. Dragging a Files row to a message box still adds an `@mention`. In the desktop app on Mac and Windows, file links in chat still drag out as files instead of dropping on a pane. +- **The work area:** everything right of the thread list is one area of panes, starting as one pane with a Chat tab for the selected thread. Drag a tab onto a pane's tab strip to move it there, onto an edge of a pane's content to split that side, or onto the middle to join that pane. The tab menu also has Split right and Split down. When there is one pane, a Split right button at the right end of the tab bar splits it and opens a New tab page. Panes split again in either direction. Drag the divider between two panes, or use the arrow keys on it, to resize. Double-click the divider to reset its size. Closing a pane's last tab closes the pane. Any pane with a message box (a Chat tab, a reply tab, or a side-thread tab) stays at least 360 px wide. Drag a same-project thread from the thread list into the area to open its chat as another Chat tab. File links in that chat open that thread's file as a tab beside it. You cannot drop another project's thread into the area, though dropping it on a message box still adds it as context. A thread link, chip, or header breadcrumb in a chat opens a same-project thread as a Chat tab beside the chat, and opens a thread of another project or environment on its own page. Subagents and side chats open as side-thread tabs beside the chat, as in upstream T3 Code. A Cmd or Ctrl click, a middle click, or "Open in main view" opens them on their own page. Reply, "N replies" on a message, or a sub-thread in the Replies list opens that sub-thread as its own tab. Opening one from the Replies list places it next to the list. Each thread keeps its own layout. The last Chat tab cannot close. Closing the selected thread's Chat removes it until + → Chat brings it back. Files, links, and diffs that open by themselves go beside the chat, never over it. A window 980 px wide or less shows every tab in one strip and keeps the panes for when there is room. In that narrow view, Back shows the previous open tab, skips closed tabs, and leaves the thread after the starting tab. In wider windows, Back still moves between threads. The right panel's show, hide, and maximize controls are gone. A press anywhere on a tab switches to it at once. No tab is ever hidden except a browser or device tab playing in the floating mini player, a small floating window over the chat. "Preview: Toggle", picture-in-picture, and a device's Float move the tab into the mini player and keep the session. Closing the mini player, choosing "Open in panel", or using "Preview: Toggle" again puts the tab back in its pane. If the window or layout stops showing the Chat that holds the mini player, the tab goes back to its pane and the mini player closes. "Preview: Toggle" on an empty browser tab (a New tab page with no page loaded) closes that tab. "Diff: Toggle" closes the Diff tab when it is shown and opens it when it is not. Reopen Closed View can bring back a closed Diff tab. There is no terminal drawer under the Chat. Every terminal is a terminal tab in a pane. Project scripts and the Run button on a chat code block run in an idle terminal tab, or open a new terminal tab. A terminal that the server already runs for the thread (such as a worktree setup shell) shows as a background tab. "Terminal: Toggle" (Cmd+J or Ctrl+J) is gone, including from Settings → Keybindings. Split, new, and close terminal shortcuts act on the focused terminal tab. Drag a file from the Files tree, or a link from a chat message, onto a pane to open it there. Supported chat links are file, pull request, issue, thread, `board://`, Dashboard, and web links. Drop the item on a tab strip to open it at that spot, on one of a pane's four edges to split that side, or on the middle to add it to that pane. If the item is already open in another pane, the drop moves its tab there. If you press a key or click before a slow drop finishes opening, the item opens where a click would instead. A dropped file keeps a standalone Files tab open beside it. A plain click on a file still replaces the Files tab. A full pull request or issue URL opens as a pull request or issue tab when a click opens that kind of tab. Other web links, and pull request or issue links that do not open that kind of tab, drag whenever the preview browser is available. A drop opens those links in the preview browser even when a click opens them in the system browser. Without a preview browser, those links do not drag. Folder rows in the Files tree, short references like `#42`, commit links, and web image and video URLs do not drag. A chat file link drags whenever a click opens it in the work area. A dropped file link opens what its click opens, in the pane you chose, so it can open a workspace folder or a workspace image or video file. Dragging a Files row to a message box still adds an `@mention`. In the desktop app on Mac and Windows, file links in chat still drag out as files instead of dropping on a pane. - Copy buttons on pages in the preview browser now put the copied text into your own clipboard. - **Two preview browser modes:** Settings → Browser → Preview browser picks the browser the server runs for preview tabs. **T3 native** (fast) is the default. It runs chrome-headless-shell, Chrome's small build that runs without a window. **Chrome** (slow) runs full Chrome, for pages that don't work in T3 native. On platforms where T3 has no Chrome for Testing build (Google's Chrome build for test automation), both choices run T3 native. Switching closes the open preview tabs. - **Compact when idle for Claude threads:** a choice in Settings → Providers → Advanced → Compact idle threads. Besides compacting before the prompt cache expires, it compacts a large idle Claude thread (default 400K tokens or more) a set time (default 15 minutes) after the last message or answer from a user or a bot, so the compaction runs while no one waits for a reply. The token counts and the wait are set right under the choice. diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index e9087311abda3..0eb716294d237 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -13,6 +13,7 @@ import { useEffect, useEffectEvent, useRef } from "react"; import { isCommandPaletteOpen } from "../commandPaletteBus"; import { partitionOpenLinkedFiles } from "../fork/workArea/closedLinkedFiles"; +import { onlyOwnTabPushesSince } from "../fork/workArea/tabHistory"; import { useClosedViewStore } from "../closedViewStore"; import { useComposerDraftStore } from "../composerDraftStore"; import { environmentCatalog } from "../connection/catalog"; @@ -157,7 +158,8 @@ export function ReopenClosedViewShortcut() { return; } useClosedViewStore.getState().remove(restore.id); - if (router.history.location !== request.location) return; + if (router.history.location !== request.location && !onlyOwnTabPushesSince(request.location)) + return; let destination; if (globalPullRequests) { diff --git a/apps/web/src/components/sidebar/mainAppLocation.ts b/apps/web/src/components/sidebar/mainAppLocation.ts index 0ef545f76b772..8ec5046a6aa04 100644 --- a/apps/web/src/components/sidebar/mainAppLocation.ts +++ b/apps/web/src/components/sidebar/mainAppLocation.ts @@ -1,5 +1,6 @@ import { useNavigate, useRouter, type AnyRouter } from "@tanstack/react-router"; +import { noteAppModalClose } from "../../fork/workArea/tabHistory"; import { GUEST_PAGE_PATH } from "../../guestPage"; import { withoutAssistantCitationHash } from "../../lib/assistantCitationNavigation"; import { resolveThreadRouteTarget, type ThreadRouteTarget } from "../../threadRoutes"; @@ -76,6 +77,7 @@ export function useCloseAppModal() { unsubscribe(); void navigate({ href }); }); + noteAppModalClose(router.history, href); router.history.go(-(steps + 1)); }; } diff --git a/apps/web/src/fork/workArea/WorkArea.tsx b/apps/web/src/fork/workArea/WorkArea.tsx index 73a2511160a0d..2a88a7bccc961 100644 --- a/apps/web/src/fork/workArea/WorkArea.tsx +++ b/apps/web/src/fork/workArea/WorkArea.tsx @@ -62,6 +62,7 @@ import { LINK_PROBE, probeLayout } from "./linkDrop.logic"; import { filesTreeOwner } from "./linkSources"; import { PanelLinkOwnerContext } from "./panelLinkDrag"; import { SecondaryChat } from "./SecondaryChat"; +import { useTabHistory } from "./tabHistory"; import { ReplyTabContext, RightPanelPaneContext, @@ -249,6 +250,7 @@ export function WorkArea(props: WorkAreaProps) { setActivePreviewTab(threadRef, focused.resourceId); } }); + useTabHistory(threadRef, narrow, (tab) => update({ type: "activate", tab })); const notePress = useStableCallback((surfaceId: string) => { const tab = surfaceTabId(surfaceId); diff --git a/apps/web/src/fork/workArea/tabHistory.browser.test.tsx b/apps/web/src/fork/workArea/tabHistory.browser.test.tsx new file mode 100644 index 0000000000000..a43290b9208fb --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.browser.test.tsx @@ -0,0 +1,966 @@ +import "~/index.css"; + +import { createBrowserHistory, RouterContextProvider } from "@tanstack/react-router"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + MessageId, + ORCHESTRATION_V2_WS_METHODS, + type OrchestrationV2Command, + type PreviewSessionSnapshot, + ThreadId, + WS_METHODS, +} from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import type * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { AppRoot } from "~/AppRoot"; +import { useClosedViewStore } from "~/closedViewStore"; +// The route loads ChatView lazily, and its first transform takes seconds; see ChatView.browser.test.tsx. +import "~/components/ChatView"; +import { startMainAppLocationTracking } from "~/components/sidebar/mainAppLocation"; +import { useThreadActions } from "~/hooks/useThreadActions"; +import { __setClientSettingsForTests } from "~/hooks/useSettings"; +import { assistantCitationNavigation } from "~/lib/assistantCitationNavigation"; +import { getRouter } from "~/router"; +import { useRightPanelStore } from "~/rightPanelStore"; +import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry"; +import { readThreadShell } from "~/state/entities"; +import { serverEnvironment } from "~/state/server"; +import { + answerRpc, + ENVIRONMENT_ID, + installFakeEnvironment, + threadWithHistory, + type FakeDriver, +} from "../../../test/fakeEnvironment"; +import { render } from "../../../test/render"; +import { tabHistoryTags } from "./tabHistoryTags"; +import { asTabId, focusedTab, resolveLayout } from "./workArea.logic"; +import { restoredRecord, restoreWorkArea } from "./workAreaStorage.logic"; +import { currentWorkAreaView } from "./workAreaView"; + +vi.mock( + "../../../../../packages/client-runtime/src/connection/driver.ts", + async (importOriginal) => { + const [actual, { fakeDriver }, Layer] = await Promise.all([ + importOriginal<{ readonly ConnectionDriver: Context.Key }>(), + import("../../../test/fakeEnvironment"), + import("effect/Layer"), + ]); + return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; + }, +); + +vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ + ...(await original()), + trackRpcRequestSent: () => {}, +})); + +const ownerThread = threadWithHistory("owner", 1); +const otherThread = threadWithHistory("other", 1); +const sideThread = { ...threadWithHistory("side", 1), sideChatOf: ownerThread.id }; +// The real server always serves thread families; the fake does when a thread is older settled. +const settledThread = { ...threadWithHistory("settled", 1), olderSettled: true as const }; +// Each is deleted by one test only, so no earlier test leaves a command waiting on its thread. +const doomedThread = threadWithHistory("doomed", 1); +const doomedOnBackThread = threadWithHistory("doomed-on-back", 1); +const doomedParentThread = threadWithHistory("doomed-parent", 1); +const doomedKidThread = { + ...threadWithHistory("doomed-kid", 1), + sideChatOf: doomedParentThread.id, +}; +// The app keeps the first test's shell and server config for the whole file, so every test serves +// the same threads. +const THREADS = [ + ownerThread, + otherThread, + sideThread, + settledThread, + doomedThread, + doomedOnBackThread, + doomedParentThread, + doomedKidThread, +]; +const threadPath = (thread: (typeof THREADS)[number]) => `/${ENVIRONMENT_ID}/${thread.id}`; +const owner = scopeThreadRef(ENVIRONMENT_ID, ownerThread.id); +const other = scopeThreadRef(ENVIRONMENT_ID, otherThread.id); +const settled = scopeThreadRef(ENVIRONMENT_ID, settledThread.id); +const doomed = scopeThreadRef(ENVIRONMENT_ID, doomedThread.id); +const doomedOnBack = scopeThreadRef(ENVIRONMENT_ID, doomedOnBackThread.id); +const doomedParent = scopeThreadRef(ENVIRONMENT_ID, doomedParentThread.id); +const doomedKid = scopeThreadRef(ENVIRONMENT_ID, doomedKidThread.id); +const OWNER_PATH = threadPath(ownerThread); +const OTHER_PATH = threadPath(otherThread); +const SETTLED_PATH = threadPath(settledThread); +const deleted = scopeThreadRef(ENVIRONMENT_ID, ThreadId.make("deleted")); +const SIDE_TAB = `thread:${sideThread.id}`; + +function setup(thread = owner) { + useRightPanelStore.setState({ + byThreadKey: { + [scopedThreadKey(thread)]: restoredRecord({ + isOpen: false, + activeSurfaceId: null, + surfaces: [ + { id: "files", kind: "files" }, + { id: "diff", kind: "diff" }, + ], + workArea: restoreWorkArea({ + root: { kind: "pane", id: "p0", tabs: ["chat", "files", "diff"], active: "chat" }, + tabs: { + chat: { kind: "primary-chat" }, + files: { kind: "surface" }, + diff: { kind: "surface" }, + }, + focused: "p0", + seq: 1, + })!, + }), + }, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); +} + +// Gives every listed thread the same Chat, Files and Diff layout. +function setupMany(...threads: (typeof owner)[]) { + setup(threads[0]); + const first = useRightPanelStore.getState().byThreadKey[scopedThreadKey(threads[0]!)]!; + useRightPanelStore.setState({ + byThreadKey: Object.fromEntries(threads.map((thread) => [scopedThreadKey(thread), first])), + }); +} + +const shownTabOf = (thread: typeof owner) => + focusedTab(resolveLayout(useRightPanelStore.getState().byThreadKey[scopedThreadKey(thread)]!)); +const shownTab = () => shownTabOf(owner); + +// Opens the owner over an entry of the other thread, so Back never leaves the test page. +async function openOwner( + width: number, + options: { + readonly deletedEntries?: number; + readonly thread?: typeof ownerThread; + // Leaves the browser entries for the caller to reset, so a new app can start on them. + readonly keepBrowserEntries?: boolean; + } = {}, +) { + const thread = options.thread ?? ownerThread; + await page.viewport(width, 900); + const startHref = window.location.href; + window.history.pushState(null, "", OTHER_PATH); + const history = createBrowserHistory(); + // Entries recorded in narrow mode on a thread that is deleted later. + for (const [index, tab] of ["chat", "files", "diff"] + .slice(0, options.deletedEntries ?? 0) + .entries()) { + history.push(`/${deleted.environmentId}/${deleted.threadId}`); + history.flush(); + tabHistoryTags.set(history.location.state, { + thread: scopedThreadKey(deleted), + tab: asTabId(tab), + ...(index > 0 ? { pushed: true } : {}), + }); + } + history.push(`/${ENVIRONMENT_ID}/${thread.id}`); + history.flush(); + const router = getRouter(history); + await router.load(); + await using stack = new AsyncDisposableStack(); + stack.defer(() => { + history.destroy(); + if (!options.keepBrowserEntries) window.history.replaceState(null, "", startHref); + }); + // AppRoot brings its own router. + stack.use(await render(, { router: false })); + await expect.element(composer(thread)).toBeVisible(); + const opened = stack.move(); + return { router, [Symbol.asyncDispose]: () => opened.disposeAsync() }; +} + +// As the delete flow does for a deleted thread. +const markDeleted = () => tabHistoryTags.markDead(scopedThreadKey(deleted)); + +// The real delete flow, run from a button beside the app, with the delete command held. Install it +// before the thread opens: the app sends commands then, and one left unanswered holds the later +// commands on its thread. +function holdDelete(target: typeof owner) { + const reply = Promise.withResolvers(); + let sent = false; + const dispatch = answerRpc( + ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + (command: OrchestrationV2Command) => { + if (command.type !== "thread.delete") return Effect.succeed({ sequence: 1 }); + sent = true; + return Effect.promise(() => reply.promise).pipe(Effect.as({ sequence: 1 })); + }, + ); + // Stopping the thread's session first reads its provider sessions. + const projection = answerRpc(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, () => + Effect.succeed({ providerSessions: [] }), + ); + const results: ReturnType["deleteThread"]>[] = []; + function DeleteButton() { + const { deleteThread } = useThreadActions(); + return ( + + ); + } + return { + render: (router: ReturnType) => + render( + + + + + , + { router: false }, + ), + start: async () => { + // The app covers this button, so the click goes to the element itself. + page + .getByRole("button", { name: "Delete thread" }) + .element() + .dispatchEvent(new MouseEvent("click", { bubbles: true })); + await expect.poll(() => sent).toBe(true); + }, + finish: async () => { + reply.resolve(); + return (await results[0])?._tag; + }, + [Symbol.dispose]: () => { + dispatch[Symbol.dispose](); + projection[Symbol.dispose](); + }, + }; +} + +// Reopen Closed View of the other thread's browser tab, with the browser restore held. +function holdBrowserReopen() { + const closedBrowser: PreviewSessionSnapshot = { + threadId: other.threadId, + tabId: "closed-tab", + navStatus: { _tag: "Idle" }, + canGoBack: false, + canGoForward: false, + updatedAt: "2026-11-24T00:00:00Z", + }; + const response = Promise.withResolvers(); + let requested = false; + const preview = answerRpc(WS_METHODS.previewOpen, () => { + requested = true; + return Effect.promise(() => response.promise); + }); + const platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + return { + remember: () => + useClosedViewStore + .getState() + .remember({ kind: "browser", threadRef: other, snapshot: closedBrowser }), + requested: () => requested, + restore: () => response.resolve({ ...closedBrowser, tabId: "restored-tab" }), + // The reopen removes its entry right before it decides whether to follow the restore. + settled: async () => { + await expect + .poll(() => + useRightPanelStore + .getState() + .byThreadKey[scopedThreadKey(other)]?.surfaces.some( + (surface) => surface.id === "browser:restored-tab", + ), + ) + .toBe(true); + await expect.poll(() => useClosedViewStore.getState().entries.length).toBe(0); + }, + [Symbol.dispose]: () => { + preview[Symbol.dispose](); + platform.mockRestore(); + }, + }; +} + +const composer = (thread: typeof ownerThread) => + page.getByRole("textbox", { name: `Message ${thread.title}` }); +const modalClose = (dialog: "Settings" | "Usage") => + page.getByRole("dialog", { name: dialog }).getByRole("button", { + name: "Close", + exact: true, + }); +const settingsClose = () => modalClose("Settings"); +const pressTab = (tab: string) => + userEvent.click( + page.elementLocator(document.querySelector(`[data-right-panel-tab-id="${tab}"]`)!), + ); +const historyIndex = () => (window.history.state as { __TSR_index: number }).__TSR_index; +const quoted = () => window.location.hash.startsWith("#assistant-citation="); +const pressReopen = () => { + const key = new KeyboardEvent("keydown", { + key: "T", + ctrlKey: true, + shiftKey: true, + bubbles: true, + cancelable: true, + }); + document.body.dispatchEvent(key); + expect(key.defaultPrevented).toBe(true); +}; + +const quoteFor = ( + thread: typeof ownerThread, + source: Parameters[1] = null, +) => + assistantCitationNavigation( + { + version: 1, + environmentId: ENVIRONMENT_ID, + threadId: thread.id, + messageId: MessageId.make(`${thread.id}-assistant-0`), + text: "Answer", + start: 0, + end: 6, + prefix: "", + suffix: "", + }, + source, + ); + +const snapshot = () => ({ + path: window.location.pathname, + index: historyIndex(), + tab: shownTab(), + quote: quoted(), + tag: tabHistoryTags.get(window.history.state)?.tab ?? null, +}); + +describe("tab history", () => { + it.each([false, true])( + "wide Back from a second thread restores the quote URL with narrow tab push %s", + async (pushTab) => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + await app.router.navigate(quoteFor(ownerThread)); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: 2, quote: true }); + if (pushTab) { + await pressTab("files"); + await expect.poll(snapshot).toMatchObject({ index: 3, quote: false, tab: "files" }); + } + await app.router.navigate({ href: OTHER_PATH }); + await expect.element(composer(otherThread)).toBeVisible(); + await page.viewport(1400, 900); + await expect.poll(() => currentWorkAreaView().narrow).toBe(false); + + const at = () => ({ path: window.location.pathname, index: historyIndex(), quote: quoted() }); + window.history.back(); + await expect.poll(at).toEqual({ path: OWNER_PATH, index: 2, quote: true }); + window.history.back(); + await expect.poll(at).toEqual({ path: OWNER_PATH, index: 1, quote: false }); + }, + ); + + it("Back passes three entries of a deleted thread on a server with thread families", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800, { deletedEntries: 3 }); + await expect + .poll( + () => + appAtomRegistry.get(serverEnvironment.configValueAtom(ENVIRONMENT_ID)) + ?.shellThreadFamilies, + ) + .toBe(true); + markDeleted(); + expect(historyIndex()).toBe(4); + + window.history.back(); + await expect.element(composer(otherThread)).toBeVisible(); + expect([historyIndex(), app.router.state.location.pathname]).toEqual([0, OTHER_PATH]); + }); + + it("Back passes a deleted thread's entries with no work area mounted", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800, { deletedEntries: 3 }); + await app.router.navigate({ to: "/workflows", replace: true }); + await expect.element(composer(ownerThread)).not.toBeInTheDocument(); + markDeleted(); + + window.history.back(); + await expect.element(composer(otherThread)).toBeVisible(); + expect([historyIndex(), app.router.state.location.pathname]).toEqual([0, OTHER_PATH]); + }); + + it("steps Back through narrow tab presses, skips a closed tab, then leaves the thread", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + + window.history.back(); + await expect.poll(shownTab).toBe("files"); + window.history.forward(); + await expect.poll(shownTab).toBe("diff"); + + useRightPanelStore.getState().closeSurface(owner, "files"); + window.history.back(); + await expect.poll(shownTab).toBe("chat"); + expect(historyIndex()).toBe(1); + expect(tabHistoryTags.get(window.history.state)).toEqual({ + thread: scopedThreadKey(owner), + tab: "chat", + }); + + window.history.back(); + await expect.element(composer(otherThread)).toBeVisible(); + expect(app.router.state.location.pathname).toBe(OTHER_PATH); + }); + + it("pushes nothing for desktop tab presses, so Back leaves the thread", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(1400); + const length = window.history.length; + + await pressTab("files"); + await expect.poll(shownTab).toBe("files"); + await pressTab("diff"); + await expect.poll(shownTab).toBe("diff"); + await pressTab("chat"); + await expect.poll(shownTab).toBe("chat"); + expect(historyIndex()).toBe(1); + + window.history.back(); + await expect.element(composer(otherThread)).toBeVisible(); + expect(app.router.state.location.pathname).toBe(OTHER_PATH); + expect([historyIndex(), window.history.length]).toEqual([0, length]); + }); + + it("wide Back crosses the entries narrow tab presses left", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using _app = await openOwner(800); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + await page.viewport(1400, 900); + await expect.poll(() => currentWorkAreaView().narrow).toBe(false); + + window.history.back(); + await expect.poll(() => window.location.pathname).toBe(OTHER_PATH); + }); + + it("wide Back crosses tab entries pushed from a quote entry", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + await app.router.navigate({ ...quoteFor(ownerThread), replace: true }); + expect(snapshot()).toMatchObject({ index: 1, quote: true, tab: "chat" }); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + await page.viewport(1400, 900); + await expect.poll(() => currentWorkAreaView().narrow).toBe(false); + + window.history.back(); + await expect.poll(() => window.location.pathname).toBe(OTHER_PATH); + expect(historyIndex()).toBe(0); + }); + + it("keeps narrow Back and Forward tab stops after clicking Settings Close", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + using _tracking = { [Symbol.dispose]: startMainAppLocationTracking(app.router) }; + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + const length = window.history.length; + await app.router.navigate({ href: "/settings/general" }); + const close = settingsClose(); + await expect.element(close).toBeVisible(); + await userEvent.click(close); + await expect.element(close).not.toBeInTheDocument(); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: 3, tab: "diff" }); + // Settings left Forward history: the entry count is back to what it was before it opened. + expect(window.history.length).toBe(length); + + window.history.back(); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: 2, tab: "files" }); + window.history.forward(); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: 3, tab: "diff" }); + }); + + it("pushes tab presses made on a main-chat quote, and Back steps through the quote", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + await app.router.navigate(quoteFor(ownerThread)); + await expect.poll(quoted).toBe(true); + expect(historyIndex()).toBe(2); + + await pressTab("files"); + await expect.poll(historyIndex).toBe(3); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(4); + expect(quoted()).toBe(false); + + window.history.back(); + await expect.poll(shownTab).toBe("files"); + window.history.back(); + await expect.poll(shownTab).toBe("chat"); + expect([historyIndex(), quoted()]).toEqual([2, true]); + + // Back from the quote stays on this thread: Forward from there reaches the quote again. + window.history.back(); + await expect.poll(historyIndex).toBe(1); + window.history.forward(); + await expect.poll(historyIndex).toBe(2); + expect([shownTab(), quoted(), app.router.state.location.pathname]).toEqual([ + "chat", + true, + OWNER_PATH, + ]); + }); + + it("records a manual narrow switch to the side-chat tab named by the current quote", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(1400); + const shell = readThreadShell(scopeThreadRef(ENVIRONMENT_ID, sideThread.id)); + expect(shell?.lineage.parentThreadId).toBe(ownerThread.id); + await app.router.navigate({ ...quoteFor(sideThread, shell), replace: true }); + await expect.poll(shownTab).toBe(SIDE_TAB); + await pressTab("files"); + await expect.poll(shownTab).toBe("files"); + expect(snapshot()).toMatchObject({ index: 1, quote: true }); + await page.viewport(800, 900); + await expect.poll(() => snapshot().tag).toBe("files"); + + await pressTab(SIDE_TAB); + await expect.poll(historyIndex).toBe(2); + // Back stays on the thread, at the quote entry, where the quote shows its side chat again. + window.history.back(); + await expect + .poll(snapshot) + .toMatchObject({ path: OWNER_PATH, index: 1, tab: SIDE_TAB, quote: true }); + }); + + it("Back onto a side-chat quote whose tab was closed lets the quote show it again", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + const shell = readThreadShell(scopeThreadRef(ENVIRONMENT_ID, sideThread.id)); + expect(shell?.lineage.parentThreadId).toBe(ownerThread.id); + await app.router.navigate(quoteFor(sideThread, shell)); + await expect.poll(shownTab).toBe(SIDE_TAB); + await expect.poll(() => snapshot().tag).toBe(SIDE_TAB); + expect(historyIndex()).toBe(3); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(4); + useRightPanelStore.getState().closeSurface(owner, SIDE_TAB); + + // The quote's own reveal shows its side chat again and records it on the quote entry. + window.history.back(); + await expect + .poll(snapshot) + .toMatchObject({ path: OWNER_PATH, index: 3, quote: true, tab: SIDE_TAB, tag: SIDE_TAB }); + }); + + it("puts a same-thread Reopen Closed View on the narrow Back stack", async () => { + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + using _environment = installFakeEnvironment(THREADS); + setup(); + await using _app = await openOwner(800); + useRightPanelStore.getState().closeSurface(owner, "diff"); + useClosedViewStore.setState({ entries: [] }); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + useClosedViewStore.getState().remember({ + kind: "panel-tab", + threadRef: owner, + surface: { id: "diff", kind: "diff" }, + }); + + pressReopen(); + await expect.poll(shownTab).toBe("diff"); + await expect.poll(historyIndex).toBe(3); + window.history.back(); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: 2, tab: "files" }); + expect( + useRightPanelStore + .getState() + .byThreadKey[scopedThreadKey(owner)]?.surfaces.some((surface) => surface.id === "diff"), + ).toBe(true); + }); + + it("Back after a narrow Reopen Closed View returns to the tab shown before it", async () => { + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + useRightPanelStore.getState().closeSurface(owner, "diff"); + useClosedViewStore.setState({ entries: [] }); + useClosedViewStore.getState().remember({ + kind: "panel-tab", + threadRef: owner, + surface: { id: "diff", kind: "diff" }, + }); + expect([shownTab(), historyIndex()]).toEqual(["chat", 1]); + + pressReopen(); + await expect.poll(shownTab).toBe("diff"); + await expect.poll(historyIndex).toBe(2); + window.history.back(); + await expect.poll(shownTab).toBe("chat"); + expect([historyIndex(), app.router.state.location.pathname]).toEqual([1, OWNER_PATH]); + }); + + it.each([1400, 800])( + "lets a queued reopen follow its browser restore to the other thread at width %i", + async (width) => { + using _environment = installFakeEnvironment(THREADS); + using reopen = holdBrowserReopen(); + setup(); + await using app = await openOwner(width); + useRightPanelStore.getState().closeSurface(owner, "diff"); + useClosedViewStore.setState({ entries: [] }); + reopen.remember(); + useClosedViewStore.getState().remember({ + kind: "panel-tab", + threadRef: owner, + surface: { id: "diff", kind: "diff" }, + }); + + // Reopen Closed View twice: Diff here first, then the other thread's browser tab. + pressReopen(); + pressReopen(); + await expect.poll(reopen.requested).toBe(true); + await expect.poll(shownTab).toBe("diff"); + // Narrow mode records the reopened Diff tab as a tab entry. + await expect.poll(historyIndex).toBe(width === 800 ? 2 : 1); + + reopen.restore(); + await reopen.settled(); + expect(app.router.history.location.pathname).toBe(OTHER_PATH); + }, + ); + + it.each([1, 2])( + "keeps a user's Back to entry %i while a Reopen Closed View request is pending", + async (destinationIndex) => { + using _environment = installFakeEnvironment(THREADS); + using reopen = holdBrowserReopen(); + setup(); + await using app = await openOwner(800); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + if (destinationIndex === 2) { + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + } + useClosedViewStore.setState({ entries: [] }); + reopen.remember(); + pressReopen(); + await expect.poll(reopen.requested).toBe(true); + + window.history.back(); + const tab = destinationIndex === 2 ? "files" : "chat"; + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: destinationIndex, tab }); + reopen.restore(); + await reopen.settled(); + expect({ + pathname: app.router.history.location.pathname, + index: app.router.history.location.state.__TSR_index, + tab: shownTab(), + }).toEqual({ pathname: OWNER_PATH, index: destinationIndex, tab }); + }, + ); + + it.each([false, true])( + "lets a thread switch win over a pending reopen, with a tab press after the switch: %s", + async (pressAfterSwitch) => { + using _environment = installFakeEnvironment(THREADS); + using reopen = holdBrowserReopen(); + setupMany(owner, settled); + await using app = await openOwner(800); + useClosedViewStore.setState({ entries: [] }); + reopen.remember(); + + pressReopen(); + await expect.poll(reopen.requested).toBe(true); + await app.router.navigate({ href: SETTLED_PATH }); + await expect.element(composer(settledThread)).toBeVisible(); + expect(historyIndex()).toBe(2); + if (pressAfterSwitch) { + await pressTab("files"); + await expect.poll(historyIndex).toBe(3); + } + + reopen.restore(); + await reopen.settled(); + expect(app.router.history.location.pathname).toBe(SETTLED_PATH); + }, + ); + + it.each([800, 1400])( + "lets Settings open and Close win over a pending reopen at width %i", + async (width) => { + using _environment = installFakeEnvironment(THREADS); + using reopen = holdBrowserReopen(); + setup(); + await using app = await openOwner(width); + using _tracking = { [Symbol.dispose]: startMainAppLocationTracking(app.router) }; + await pressTab("files"); + await expect.poll(shownTab).toBe("files"); + useClosedViewStore.setState({ entries: [] }); + reopen.remember(); + pressReopen(); + await expect.poll(reopen.requested).toBe(true); + await app.router.navigate({ href: "/settings/general" }); + const close = settingsClose(); + await expect.element(close).toBeVisible(); + await userEvent.click(close); + await expect.element(close).not.toBeInTheDocument(); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, tab: "files" }); + + reopen.restore(); + await reopen.settled(); + expect(app.router.history.location.pathname).toBe(OWNER_PATH); + }, + ); + + it("records a tab press even if a non-user reveal runs before the history write", async () => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using _app = await openOwner(800); + const observations: string[] = []; + const stop = useRightPanelStore.subscribe(() => { + if (shownTab() !== "files") return; + stop(); + queueMicrotask(() => { + observations.push(shownTab()); + useRightPanelStore.getState().revealSurface(owner, "diff"); + observations.push(shownTab()); + }); + }); + + try { + await pressTab("files"); + } finally { + stop(); + } + await expect.poll(historyIndex).toBe(2); + expect({ observations, ...snapshot() }).toMatchObject({ + observations: ["files", "diff"], + tab: "diff", + tag: "files", + }); + window.history.back(); + await expect.poll(shownTab).toBe("chat"); + window.history.forward(); + await expect.poll(historyIndex).toBe(2); + await expect.poll(shownTab).toBe("files"); + }); + + it("still opens the next thread when a tab press lands while the shown thread is deleted", async () => { + using _environment = installFakeEnvironment(THREADS); + using deletion = holdDelete(doomed); + setup(doomed); + await using app = await openOwner(800, { thread: doomedThread }); + await using _button = await deletion.render(app.router); + + await deletion.start(); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + expect(shownTabOf(doomed)).toBe("files"); + expect(await deletion.finish()).toBe("Success"); + + // The delete's fallback replaces the tab entry with the next thread. + await expect.poll(() => app.router.state.location.pathname).not.toBe(threadPath(doomedThread)); + expect(THREADS.map(threadPath)).toContain(app.router.state.location.pathname); + expect(historyIndex()).toBe(2); + }); + + it("still opens the next thread when a narrow Back lands while the shown thread is deleted", async () => { + using _environment = installFakeEnvironment(THREADS); + using deletion = holdDelete(doomedOnBack); + setup(doomedOnBack); + await using app = await openOwner(800, { thread: doomedOnBackThread }); + await using _button = await deletion.render(app.router); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + + await deletion.start(); + // In narrow mode, Back is a tab step inside the thread, like a tab press. + window.history.back(); + await expect.poll(() => shownTabOf(doomedOnBack)).toBe("chat"); + expect([historyIndex(), app.router.state.location.pathname]).toEqual([ + 1, + threadPath(doomedOnBackThread), + ]); + expect(await deletion.finish()).toBe("Success"); + + await expect + .poll(() => app.router.state.location.pathname) + .not.toBe(threadPath(doomedOnBackThread)); + expect(THREADS.map(threadPath)).toContain(app.router.state.location.pathname); + }); + + it("Back passes a deleted thread's saved tab entries after a reload", async () => { + using _environment = installFakeEnvironment(THREADS); + using deletion = holdDelete(deleted); + setup(deleted); + // As after a reload: the panel record and the entries' tags remain, the revision counts do not. + useRightPanelStore.setState({ + userActionRevisionByThreadKey: {}, + closeRevisionByThreadKey: {}, + }); + await using app = await openOwner(800, { deletedEntries: 3 }); + expect(useRightPanelStore.getState().byThreadKey[scopedThreadKey(deleted)]).toBeDefined(); + expect(historyIndex()).toBe(4); + await using _button = await deletion.render(app.router); + await deletion.start(); + expect(await deletion.finish()).toBe("Success"); + expect(useRightPanelStore.getState().byThreadKey[scopedThreadKey(deleted)]).toBeUndefined(); + + window.history.back(); + await expect + .poll(() => [historyIndex(), app.router.history.location.pathname]) + .toEqual([0, OTHER_PATH]); + }); + + it.each([false, true])( + "wide Back from Workflows reaches the quote entry, with the app mounted fresh on Workflows: %s", + async (fresh) => { + using _environment = installFakeEnvironment(THREADS); + setup(); + const startHref = window.location.href; + await using stack = new AsyncDisposableStack(); + stack.defer(() => window.history.replaceState(null, "", startHref)); + const app = stack.use(await openOwner(800, { keepBrowserEntries: true })); + await app.router.navigate(quoteFor(ownerThread)); + await expect.poll(snapshot).toMatchObject({ index: 2, quote: true }); + await pressTab("files"); + await expect.poll(snapshot).toMatchObject({ index: 3, quote: false, tab: "files" }); + await app.router.navigate({ href: "/workflows" }); + await expect.element(composer(ownerThread)).not.toBeInTheDocument(); + await page.viewport(1400, 900); + expect(historyIndex()).toBe(4); + if (fresh) { + // As after a reload: a new router and app over the same browser entries and saved tags, + // with no work area mounted. + await app[Symbol.asyncDispose](); + const history = createBrowserHistory(); + stack.defer(() => history.destroy()); + const router = getRouter(history); + await router.load(); + stack.use(await render(, { router: false })); + expect(router.state.location.pathname).toBe("/workflows"); + } + + window.history.back(); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: 2, quote: true }); + }, + ); + + it.each([OTHER_PATH, "/settings/general"])( + "keeps Forward history after a Back-menu jump from %s to an earlier tab entry", + async (startPath) => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(800); + using _tracking = { [Symbol.dispose]: startMainAppLocationTracking(app.router) }; + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + await app.router.navigate({ href: startPath }); + await expect.poll(() => app.router.state.location.pathname).toBe(startPath); + expect(historyIndex()).toBe(4); + + // A pick two entries back in the browser's Back menu is one native jump. + window.history.go(-2); + await expect.poll(snapshot).toMatchObject({ path: OWNER_PATH, index: 2, tag: "files" }); + window.history.go(2); + await expect.poll(() => [window.location.pathname, historyIndex()]).toEqual([startPath, 4]); + }, + ); + + it.each([ + { presses: 0, modal: "/settings/general", dialog: "Settings" }, + { presses: 1, modal: "/settings/general", dialog: "Settings" }, + { presses: 2, modal: "/settings/general", dialog: "Settings" }, + { presses: 1, modal: "/usage", dialog: "Usage" }, + ] as const)( + "drops $modal from Forward when its Close runs in a wide window after $presses narrow tab presses", + async ({ presses, modal, dialog }) => { + using _environment = installFakeEnvironment(THREADS); + setup(); + await using app = await openOwner(presses === 0 ? 1400 : 800); + using _tracking = { [Symbol.dispose]: startMainAppLocationTracking(app.router) }; + if (presses >= 1) { + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + } + if (presses >= 2) { + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + window.history.back(); + await expect.poll(snapshot).toMatchObject({ index: 2, tab: "files" }); + } + await page.viewport(1400, 900); + await expect.poll(() => currentWorkAreaView().narrow).toBe(false); + const tab = shownTab(); + await app.router.navigate({ href: modal }); + const close = modalClose(dialog); + await expect.element(close).toBeVisible(); + await userEvent.click(close); + await expect.element(close).not.toBeInTheDocument(); + + // With nothing ahead, Forward stays on the thread. + await expect + .poll(() => ({ path: window.location.pathname, forward: navigation.canGoForward })) + .toEqual({ path: OWNER_PATH, forward: false }); + expect(shownTab()).toBe(tab); + }, + ); + + it("Back passes a side chat's tab entries after its parent thread is deleted", async () => { + using _environment = installFakeEnvironment(THREADS); + using deletion = holdDelete(doomedParent); + setupMany(doomedKid, owner); + await using app = await openOwner(800, { thread: doomedKidThread }); + await using _button = await deletion.render(app.router); + await pressTab("files"); + await expect.poll(historyIndex).toBe(2); + await pressTab("diff"); + await expect.poll(historyIndex).toBe(3); + await app.router.navigate({ href: OWNER_PATH }); + await expect.element(composer(ownerThread)).toBeVisible(); + expect(historyIndex()).toBe(4); + expect(readThreadShell(doomedKid)?.lineage.parentThreadId).toBe(doomedParentThread.id); + + // The server deletes the side chat with its parent. + await deletion.start(); + expect(await deletion.finish()).toBe("Success"); + + window.history.back(); + await expect.poll(() => [historyIndex(), window.location.pathname]).toEqual([0, OTHER_PATH]); + }); +}); diff --git a/apps/web/src/fork/workArea/tabHistory.logic.test.ts b/apps/web/src/fork/workArea/tabHistory.logic.test.ts new file mode 100644 index 0000000000000..a7339ff6f4b67 --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.logic.test.ts @@ -0,0 +1,1109 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { MessageId, ThreadId } from "@t3tools/contracts"; +import { + type AnyRouter, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from "@tanstack/react-router"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { assistantCitationRoute } from "~/lib/assistantCitationNavigation"; + +import { + decideHistoryMove, + decideMove, + type HistoryMove, + isTabStep, + type Move, + planPush, + readTabEntry, + type Shown, + type TabEntry, + userShownTabChange, +} from "./tabHistory.logic"; +import { + isWorkAreaTabStep, + markTabHistoryThreadDeleted, + noteAppModalClose, + onlyOwnTabPushesSince, + watchTabHistory, +} from "./tabHistory"; +import { createTabTags, tabHistoryTags, type TabTags } from "./tabHistoryTags"; +import { asTabId, DEFAULT_LAYOUT, focusedTab, PRIMARY_CHAT, replyTabId } from "./workArea.logic"; +import { + change, + layout, + onePane, + other, + ref, + resetWorkAreaStore, + store, + third, +} from "./workAreaTestKit"; +import { publishWorkAreaView } from "./workAreaView"; + +const KEY = scopedThreadKey(ref); +const THREAD = `/${ref.environmentId}/${ref.threadId}`; +const OTHER = `/${other.environmentId}/${other.threadId}`; +const A = asTabId("file:a.ts"); +const B = asTabId("file:b.ts"); +const C = asTabId("file:c.ts"); +const entry = (tab: string, thread = KEY): TabEntry => ({ thread, tab: asTabId(tab) }); +const pushed = (tab: string, thread = KEY): TabEntry => ({ ...entry(tab, thread), pushed: true }); +const entryState = (key: string) => ({ __TSR_index: 0, key, __TSR_key: key }); +const memoryStorage = () => { + const items = new Map(); + return { + getItem: (key: string) => items.get(key) ?? null, + setItem: (key: string, value: string) => void items.set(key, value), + }; +}; + +beforeEach(resetWorkAreaStore); + +describe("readTabEntry", () => { + it.each([ + { value: { thread: KEY, tab: "chat" }, read: entry("chat") }, + { value: { thread: KEY, tab: "chat", extra: 3 }, read: entry("chat") }, + { value: undefined, read: null }, + { value: null, read: null }, + { value: "chat", read: null }, + { value: [KEY, "chat"], read: null }, + { value: { thread: KEY }, read: null }, + { value: { thread: KEY, tab: 3 }, read: null }, + { value: { thread: null, tab: "chat" }, read: null }, + { value: { thread: KEY, tab: "chat", pushed: true }, read: pushed("chat") }, + { value: { thread: KEY, tab: "chat", dead: true }, read: { ...entry("chat"), dead: true } }, + { value: { thread: KEY, tab: "chat", pushed: false }, read: null }, + { value: { thread: KEY, tab: "chat", dead: "yes" }, read: null }, + ])("reads $value as $read", ({ value, read }) => { + expect(readTabEntry(value)).toEqual(read); + }); +}); + +describe("createTabTags", () => { + it("reads its tags back from storage and keeps the newest 500", () => { + const storage = memoryStorage(); + const tags = createTabTags(() => storage); + for (let n = 0; n <= 500; n++) tags.set(entryState(`key-${n}`), entry("chat")); + tags.set(entryState("key-1"), entry(A)); + + const reloaded = createTabTags(() => storage); + expect( + ["key-0", "key-1", "key-2", "key-500"].map((key) => reloaded.get(entryState(key))), + ).toEqual([null, entry(A), entry("chat"), entry("chat")]); + }); + + it("marks every tag of a thread dead and keeps the mark across a reload", () => { + const storage = memoryStorage(); + const tags = createTabTags(() => storage); + tags.set(entryState("base"), entry("chat")); + tags.set(entryState("push"), pushed(A)); + tags.set(entryState("other"), entry("chat", "env-1:thread-other")); + tags.markDead(KEY); + + const reloaded = createTabTags(() => storage); + expect(["base", "push", "other"].map((key) => reloaded.get(entryState(key)))).toEqual([ + { ...entry("chat"), dead: true }, + { ...pushed(A), dead: true }, + entry("chat", "env-1:thread-other"), + ]); + }); + + const blocked = () => { + throw new Error("blocked"); + }; + it.each([ + { name: "text that is not JSON", storage: { getItem: () => "[", setItem: () => {} } }, + { name: "an object", storage: { getItem: () => "{}", setItem: () => {} } }, + { + name: "bad rows", + storage: { + getItem: () => `[5, ["key"], [7, ${JSON.stringify(entry(B))}], ["key", {"thread": 1}]]`, + setItem: () => {}, + }, + }, + { name: "blocked storage", storage: { getItem: blocked, setItem: blocked } }, + ])("ignores $name and still records tags", ({ storage }) => { + const tags = createTabTags(() => storage); + expect(tags.get(entryState("key"))).toBeNull(); + tags.set(entryState("key"), entry(A)); + expect(tags.get(entryState("key"))).toEqual(entry(A)); + }); +}); + +describe("planPush", () => { + const plain = (tag: TabEntry | null) => ({ tag, reveal: false }); + it.each([ + { + name: "retags an untagged entry with the tab left", + current: plain(null), + plan: { type: "push", retag: entry("chat"), push: pushed(A) }, + }, + { + name: "keeps an entry that already names the tab left", + current: plain(entry("chat")), + plan: { type: "push", retag: null, push: pushed(A) }, + }, + { + name: "retags a stale entry", + current: plain(entry(B)), + plan: { type: "push", retag: entry("chat"), push: pushed(A) }, + }, + { + name: "keeps the mark of a stale entry it pushed", + current: plain(pushed(B)), + plan: { type: "push", retag: pushed("chat"), push: pushed(A) }, + }, + { + name: "retags another thread's entry", + current: plain(pushed("chat", "env-1:thread-other")), + plan: { type: "push", retag: entry("chat"), push: pushed(A) }, + }, + { + name: "retags a quote entry for its own reveal", + current: { tag: entry("chat"), reveal: true }, + plan: { type: "retag", retag: entry(A) }, + }, + ])("$name", ({ current, plan }) => { + expect(planPush(current, KEY, { from: PRIMARY_CHAT, to: A })).toEqual(plan); + }); + + it("writes nothing when the shown tab came back", () => { + expect(planPush(plain(null), KEY, { from: A, to: A })).toBeNull(); + expect(planPush({ tag: null, reveal: true }, KEY, { from: A, to: A })).toBeNull(); + }); +}); + +describe("decideMove", () => { + // [chat, a.ts, b.ts], b.ts shown. + const threeTabs = () => { + onePane("a.ts", "b.ts"); + return layout(); + }; + const move = (over: Partial = {}): Move => ({ + entry: entry(A), + samePath: true, + sameHref: true, + moved: true, + ...over, + }); + const deadEntry = move({ entry: { ...entry(A, "env-1:thread-gone"), dead: true } }); + + it.each([ + { name: "shows an open tab", move: move(), decision: { type: "show", tab: A } }, + { name: "skips a closed tab", move: move({ entry: entry(C) }), decision: { type: "skip" } }, + { + name: "skips the tab already shown", + move: move({ entry: entry(B) }), + decision: { type: "skip" }, + }, + { + name: "shows an open tab on an entry with another URL", + move: move({ sameHref: false }), + decision: { type: "show", tab: A }, + }, + { + name: "leaves a closed tab on an entry with another URL to the router", + move: move({ entry: entry(C), sameHref: false }), + decision: { type: "none" }, + }, + { + name: "leaves an entry with another URL and the tab already shown to the router", + move: move({ entry: entry(B), sameHref: false }), + decision: { type: "none" }, + }, + { + name: "ignores a move that stayed", + move: move({ moved: false }), + decision: { type: "none" }, + }, + { + name: "ignores a move to another path", + move: move({ samePath: false }), + decision: { type: "none" }, + }, + { + name: "ignores another thread's entry", + move: move({ entry: entry(A, "env-1:thread-other") }), + decision: { type: "none" }, + }, + { name: "ignores an untagged entry", move: move({ entry: null }), decision: { type: "none" } }, + { + name: "leaves a deleted thread's entry to the history listener", + move: deadEntry, + decision: { type: "none" }, + }, + ])("$name", ({ move: theMove, decision }) => { + const shown: Shown = { thread: KEY, layout: threeTabs() }; + expect(decideMove(theMove, shown)).toEqual(decision); + }); + + it("reads a thread with no record as the default layout", () => { + const shown: Shown = { thread: KEY, layout: DEFAULT_LAYOUT }; + expect(decideMove(move({ entry: entry("chat") }), shown)).toEqual({ type: "skip" }); + }); +}); + +describe("decideHistoryMove", () => { + const move = (over: Partial = {}): HistoryMove => ({ + entry: entry(A), + samePath: true, + moved: true, + origin: null, + ...over, + }); + const dead = { ...pushed(A, "env-1:thread-gone"), dead: true as const }; + const otherThread = "env-1:thread-other"; + + it.each([ + { name: "skips a deleted thread's entry", move: move({ entry: dead }), skip: "skip" }, + { + name: "ignores a deleted thread's entry it did not move to", + move: move({ entry: dead, moved: false }), + skip: "none", + }, + { + name: "leaves a pushed entry to the thread's view", + move: move({ entry: pushed(A) }), + skip: "none", + }, + { + name: "leaves a base to the thread's view", + move: move({ entry: entry("chat"), origin: pushed(B) }), + skip: "none", + }, + ])("narrow: $name", ({ move: theMove, skip }) => { + expect(decideHistoryMove(theMove, false)).toBe(skip); + }); + + it.each([ + { name: "skips a pushed entry", move: move({ entry: pushed(A) }), skip: "skip" }, + { + name: "skips another thread's pushed entry", + move: move({ entry: pushed(A, otherThread), samePath: false }), + skip: "skip", + }, + { name: "skips a deleted thread's entry", move: move({ entry: dead }), skip: "skip" }, + { + name: "skips the base of a Back that started on a pushed entry", + move: move({ entry: entry("chat"), origin: pushed(B) }), + skip: "skip-base", + }, + { + name: "skips an untagged base of a Back that started on a pushed entry", + move: move({ entry: null, origin: pushed(B) }), + skip: "skip-base", + }, + { name: "stops at an entry it did not push", move: move(), skip: "none" }, + { + name: "stops at a base when the Back started on an entry it did not push", + move: move({ entry: entry("chat"), origin: entry(B) }), + skip: "none", + }, + { + name: "stops at another path with a base ahead", + move: move({ entry: null, samePath: false, origin: pushed(B) }), + skip: "none", + }, + { + name: "stops at another thread's entry with a base ahead", + move: move({ entry: entry("chat", otherThread), origin: pushed(B) }), + skip: "none", + }, + { + name: "ignores a pushed entry it did not move to", + move: move({ entry: pushed(A), moved: false }), + skip: "none", + }, + ])("wide: $name", ({ move: theMove, skip }) => { + expect(decideHistoryMove(theMove, true)).toBe(skip); + }); +}); + +describe("isTabStep", () => { + const move = { entry: entry(A), samePath: true, moved: true }; + it.each([ + { name: "a step between two entries of a thread", move, left: pushed(B), step: true }, + { + name: "a step to another path", + move: { ...move, samePath: false }, + left: entry(B), + step: false, + }, + { + name: "a step to an untagged entry", + move: { ...move, entry: null }, + left: entry(B), + step: false, + }, + { name: "a step from an untagged entry", move, left: null, step: false }, + { + name: "a step from another thread's entry", + move, + left: entry(B, "env-1:thread-other"), + step: false, + }, + { name: "a step that stayed", move: { ...move, moved: false }, left: entry(B), step: false }, + ])("calls $name a tab step: $step", ({ move: theMove, left, step }) => { + expect(isTabStep(theMove, left)).toBe(step); + }); +}); + +describe("userShownTabChange", () => { + const terminal = () => + store().byThreadKey[KEY]!.surfaces.find((surface) => surface.kind === "terminal")!.id; + const counted = (act: () => void) => { + onePane("a.ts"); + store().openTerminal(ref, "term-1"); + store().activateSurface(ref, "file:a.ts"); + const prev = store(); + act(); + return userShownTabChange(prev, store(), KEY); + }; + + it.each([ + { + name: "a press on a display tab", + act: () => change({ type: "activate", tab: PRIMARY_CHAT }), + }, + { + name: "a press on a surface tab", + act: () => store().activateSurface(ref, terminal()), + }, + { name: "an open", act: () => store().openFile(ref, "b.ts") }, + ])("counts $name", ({ act }) => { + publishWorkAreaView({ narrow: true, size: null }); + const shown = counted(act); + expect(shown).toEqual({ from: A, to: focusedTab(layout()) }); + expect(shown?.to).not.toBe(A); + }); + + it.each([ + { name: "a close", act: () => store().closeSurface(ref, "file:a.ts") }, + { name: "an agent reveal", act: () => store().revealSurface(ref, terminal()) }, + { name: "an automatic open", act: () => store().open(ref, "diff", true) }, + { name: "a user mark alone", act: () => void store().markUserAction(ref) }, + { name: "another thread's open", act: () => store().openFile(other, "b.ts") }, + { name: "removing the deleted thread", act: () => store().removeThread(ref) }, + ])("ignores $name", ({ act }) => { + publishWorkAreaView({ narrow: true, size: null }); + expect(counted(act)).toBeNull(); + }); + + it("counts the first open of a thread with no record", () => { + const prev = store(); + store().openFile(ref, "a.ts"); + expect(userShownTabChange(prev, store(), KEY)).toEqual({ from: PRIMARY_CHAT, to: A }); + }); +}); + +function threadRouter(entries: readonly string[], basepath?: string) { + const root = createRootRoute(); + const chat = createRoute({ getParentRoute: () => root, id: "_chat" }); + const thread = createRoute({ getParentRoute: () => chat, path: "$environmentId/$threadId" }); + const draft = createRoute({ getParentRoute: () => chat, path: "draft/$draftId" }); + const settings = createRoute({ getParentRoute: () => chat, path: "settings" }); + return createRouter({ + routeTree: root.addChildren([chat.addChildren([thread, draft, settings])]), + history: createMemoryHistory({ initialEntries: [...entries] }), + ...(basepath === undefined ? {} : { basepath }), + }); +} + +const SIDE = ThreadId.make("thread-side"); +const SIDE_TAB = asTabId(`thread:${SIDE}`); +const THIRD = `/${third.environmentId}/${third.threadId}`; +const quoteHash = (threadId: ThreadId) => + assistantCitationRoute( + { + version: 1, + environmentId: ref.environmentId, + threadId, + messageId: MessageId.make("assistant-1"), + text: "quote", + start: 0, + end: 5, + prefix: "", + suffix: "", + }, + null, + ).hash; + +describe("watchTabHistory", () => { + let tags: TabTags; + let input: EventTarget; + // The window's width, which the last watcher started follows, as WorkArea's does. + let narrowWindow: boolean; + beforeEach(() => { + vi.useFakeTimers(); + tags = createTabTags(() => undefined); + input = new EventTarget(); + narrowWindow = true; + // [chat, a.ts, b.ts, c.ts], Chat shown. + onePane("a.ts", "b.ts", "c.ts"); + change({ type: "activate", tab: PRIMARY_CHAT }); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + const shown = () => focusedTab(layout()); + // Runs the push timers and the skip microtasks. + const settle = () => vi.runAllTimersAsync(); + // A tab press, with the pointer input that comes before it. + const press = async (tab: string) => { + input.dispatchEvent(new Event("pointerdown")); + store().activateSurface(ref, tab); + await settle(); + }; + // ChatView's reveal of a side-chat quote on its parent thread. + const revealSideChat = async () => { + store().openThread(ref, SIDE); + await settle(); + }; + const watching = (router: AnyRouter, options: { readonly narrow?: boolean } = {}): Disposable => { + narrowWindow = options.narrow ?? true; + const stop = watchTabHistory({ + router, + thread: KEY, + narrow: narrowWindow, + activate: (tab) => change({ type: "activate", tab }), + tags, + input, + isWide: () => !narrowWindow, + }); + return { [Symbol.dispose]: stop }; + }; + const at = (router: AnyRouter) => ({ + index: router.history.location.state.__TSR_index, + pathname: router.history.location.pathname, + tab: tags.get(router.history.location.state)?.tab ?? null, + }); + const back = async (router: AnyRouter) => { + router.history.back(); + await settle(); + }; + const forward = async (router: AnyRouter) => { + router.history.forward(); + await settle(); + }; + // useCloseAppModal: back to the entry before the return entry, then navigate to the thread. + const closeAppModal = async (router: AnyRouter, returnIndex: number) => { + const steps = at(router).index - returnIndex; + const unsubscribe = router.history.subscribe(() => { + unsubscribe(); + router.updateLatestLocation(); + void router.navigate({ href: THREAD }); + }); + noteAppModalClose(router.history, THREAD); + router.history.go(-(steps + 1)); + await settle(); + }; + + it("pushes each narrow tab change and steps Back through them, then out of the thread", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + + await press(A); + await press(B); + expect(at(router)).toEqual({ index: 3, pathname: THREAD, tab: B }); + expect(tags.get(router.history.location.state)).toEqual(pushed(B)); + + await back(router); + expect(shown()).toBe(A); + await back(router); + expect([shown(), at(router)]).toEqual([ + PRIMARY_CHAT, + { index: 1, pathname: THREAD, tab: "chat" }, + ]); + await back(router); + expect(at(router).pathname).toBe(OTHER); + expect(router.history.length).toBe(4); + }); + + it("skips the entry of a tab a close already shows", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(B); + await press(A); + + store().closeSurface(ref, A); + await settle(); + expect([shown(), at(router).index]).toEqual([B, 3]); + + await back(router); + expect([shown(), at(router).index]).toEqual([PRIMARY_CHAT, 1]); + }); + + it("skips closed tabs going Back and Forward", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + await press(B); + await press(C); + store().closeSurface(ref, A); + store().closeSurface(ref, B); + + await back(router); + expect([shown(), at(router).index]).toEqual([PRIMARY_CHAT, 1]); + + await forward(router); + expect([shown(), at(router).index]).toEqual([C, 4]); + }); + + it("steps Forward to an open tab and stays at the end", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + await press(B); + await back(router); + await back(router); + + await forward(router); + expect(shown()).toBe(A); + + store().closeSurface(ref, B); + await forward(router); + expect([shown(), at(router).index]).toEqual([A, 3]); + }); + + it("pushes nothing for a restore, a reveal or an automatic open", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + await back(router); + expect(router.history.length).toBe(3); + + store().revealSurface(ref, B); + store().open(ref, "diff", true); + await settle(); + expect(router.history.length).toBe(3); + expect(at(router).index).toBe(1); + }); + + it("pushes the tab the user chose when a reveal shows another before the write", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + input.dispatchEvent(new Event("pointerdown")); + store().activateSurface(ref, A); + store().revealSurface(ref, B); + await settle(); + expect([shown(), at(router)]).toEqual([B, { index: 2, pathname: THREAD, tab: A }]); + + await back(router); + expect(shown()).toBe(PRIMARY_CHAT); + await forward(router); + expect([shown(), at(router).index]).toEqual([A, 2]); + }); + + it("drops a pending push when Back or Forward arrives first", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + await press(B); + await back(router); + + store().activateSurface(ref, C); + router.history.forward(); + await settle(); + expect([router.history.length, at(router)]).toEqual([ + 4, + { index: 3, pathname: THREAD, tab: B }, + ]); + }); + + it("pushes nothing when wide, and a wide Back passes the entries left from narrow", async () => { + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router, { narrow: false }); + await press(A); + await press(B); + expect(at(router).index).toBe(1); + } + { + using _watch = watching(router); + await press(C); + await press(A); + } + using _wide = watching(router, { narrow: false }); + expect(at(router).index).toBe(3); + + await back(router); + expect(at(router)).toEqual({ index: 0, pathname: OTHER, tab: null }); + expect(shown()).toBe(A); + }); + + it("steps wide Back and Forward as if the pushed entries were not there", async () => { + // [other, thread, A, B, thread#quote, C, A]: two runs of pushes, each after its base entry. + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router); + await press(A); + await press(B); + router.history.push(`${THREAD}#${quoteHash(ref.threadId)}`); + await press(C); + await press(A); + } + using _wide = watching(router, { narrow: false }); + expect(at(router).index).toBe(6); + + // The user is on the quote entry, the second run's base, so Back reaches the first base. + await back(router); + expect(at(router).index).toBe(1); + await forward(router); + expect(at(router).index).toBe(4); + }); + + it("stops a wide Back at the base when it started on an entry it did not push", async () => { + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router); + await press(A); + await press(B); + // A second click on the open thread. + router.history.push(THREAD); + } + using _wide = watching(router, { narrow: false }); + expect(at(router).index).toBe(4); + + await back(router); + expect(at(router).index).toBe(1); + }); + + it("wide Back from another thread stops at the entry a run was pushed from, with no view of its thread", async () => { + // [other, thread, thread#quote, A, other]: no view of the thread runs after it is left. + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router); + router.history.push(`${THREAD}#${quoteHash(ref.threadId)}`); + await press(A); + } + router.history.push(OTHER); + narrowWindow = false; + expect(at(router).index).toBe(4); + + await back(router); + expect([at(router).index, router.history.location.hash]).toEqual([ + 2, + `#${quoteHash(ref.threadId)}`, + ]); + await back(router); + expect(at(router)).toEqual({ index: 1, pathname: THREAD, tab: "chat" }); + }); + + it("reports whether only our tab pushes moved history since a location", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + const start = router.history.location; + await press(A); + const afterA = router.history.location; + await press(B); + // A reopen may wait from the start of the run or from any entry the run pushed. + expect([start, afterA].map(onlyOwnTabPushesSince)).toEqual([true, true]); + + await back(router); + const backAtA = router.history.location; + expect([start, afterA, backAtA].map(onlyOwnTabPushesSince)).toEqual([false, false, false]); + await press(C); + expect(onlyOwnTabPushesSince(backAtA)).toBe(true); + + router.history.push(OTHER); + await settle(); + expect(onlyOwnTabPushesSince(backAtA)).toBe(false); + }); + + it("ends the run of our pushes when Settings closes, though it pushes a tab entry", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + const beforeSettings = router.history.location; + router.history.push("/settings"); + await closeAppModal(router, beforeSettings.state.__TSR_index); + expect(tags.get(router.history.location.state)).toEqual(pushed(A)); + + expect(onlyOwnTabPushesSince(beforeSettings)).toBe(false); + }); + + it("classifies each history event before listeners that subscribe after the first watcher", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + const steps: [string, boolean][] = []; + const unsubscribe = router.history.subscribe(({ action, location }) => { + steps.push([action.type, isWorkAreaTabStep(location)]); + }); + using _listen = { [Symbol.dispose]: unsubscribe }; + await press(A); + await press(B); + await press(C); + store().closeSurface(ref, B); + await settle(); + // Back shows A over the closed B, then the starting tab, then leaves the thread. + await back(router); + await back(router); + await back(router); + await forward(router); + router.history.push(THREAD); + await settle(); + + expect(steps).toEqual([ + ["PUSH", true], + ["PUSH", true], + ["PUSH", true], + ["BACK", true], + ["BACK", true], + ["BACK", true], + ["BACK", false], + ["FORWARD", false], + ["PUSH", false], + ]); + }); + + it("pushes a fresh entry when Settings closes, so Back, Forward and Forward again keep their tabs", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + await press(B); + const returnIndex = at(router).index; + router.history.push("/settings"); + await press(C); + expect(at(router)).toEqual({ index: returnIndex + 1, pathname: "/settings", tab: null }); + + await closeAppModal(router, returnIndex); + expect([shown(), at(router), router.history.length]).toEqual([ + C, + { index: 3, pathname: THREAD, tab: C }, + 4, + ]); + expect(tags.get(router.history.location.state)).toEqual(pushed(C)); + + await back(router); + expect([shown(), at(router).index]).toEqual([A, 2]); + await forward(router); + await forward(router); + expect([shown(), at(router)]).toEqual([C, { index: 3, pathname: THREAD, tab: C }]); + }); + + it("pushes a fresh entry when Settings closes in a wide window, so Forward has no Settings", async () => { + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router); + await press(A); + } + using _wide = watching(router, { narrow: false }); + const returnIndex = at(router).index; + router.history.push("/settings"); + + await closeAppModal(router, returnIndex); + expect([at(router), router.history.length]).toEqual([ + { index: 2, pathname: THREAD, tab: A }, + 3, + ]); + expect(tags.get(router.history.location.state)).toEqual(pushed(A)); + // One wide Back passes the fresh entry and the narrow run, and leaves the thread. + await back(router); + expect(at(router).pathname).not.toBe(THREAD); + }); + + it("pushes nothing for a GO the Close did not start, so Forward keeps its entries", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + await press(B); + router.history.push("/settings"); + + // A pick two entries back in the browser's Back menu. + router.history.go(-2); + await settle(); + expect([at(router), router.history.length]).toEqual([ + { index: 2, pathname: THREAD, tab: A }, + 5, + ]); + router.history.go(2); + await settle(); + expect(at(router)).toEqual({ index: 4, pathname: "/settings", tab: null }); + }); + + it("forgets a Close at the next history event", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + noteAppModalClose(router.history, THREAD); + router.history.push("/settings"); + + router.history.go(-1); + await settle(); + expect([at(router).index, router.history.length]).toEqual([1, 3]); + }); + + it("pushes nothing when a Close returns to a page other than the entry it lands on", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + router.history.push("/settings"); + noteAppModalClose(router.history, OTHER); + + router.history.go(-1); + await settle(); + expect([at(router), router.history.length]).toEqual([ + { index: 1, pathname: THREAD, tab: "chat" }, + 3, + ]); + }); + + it("pushes a Close's entry under the whiteboard build's basepath", async () => { + const router = threadRouter([`/chat${OTHER}`, `/chat${THREAD}`], "/chat"); + using _watch = watching(router); + await press(A); + router.history.push("/chat/settings"); + // The Close names its page as the router sees it, without the basepath. + noteAppModalClose(router.history, THREAD); + + router.history.go(-2); + await settle(); + expect([at(router), router.history.length]).toEqual([ + { index: 2, pathname: `/chat${THREAD}`, tab: A }, + 3, + ]); + expect(tags.get(router.history.location.state)).toEqual(pushed(A)); + }); + + it("tags a same-path entry another click pushes, and Back skips it", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + router.history.push(THREAD); + await settle(); + expect(at(router)).toEqual({ index: 3, pathname: THREAD, tab: A }); + expect(tags.get(router.history.location.state)).toEqual(entry(A)); + + await back(router); + expect([shown(), at(router).index]).toEqual([PRIMARY_CHAT, 1]); + }); + + it("keeps history state free of tags, so a same-path navigate adds no entry", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + await press(A); + router.updateLatestLocation(); + + await router.navigate({ href: THREAD }); + expect([router.history.length, at(router)]).toEqual([ + 3, + { index: 2, pathname: THREAD, tab: A }, + ]); + }); + + it("retags a side-chat quote for its reveal and pushes later changes without the quote", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + const hash = quoteHash(SIDE); + router.history.push(`${THREAD}#${hash}`, { assistantCitationActivation: "quote-1" }); + await revealSideChat(); + expect([shown(), at(router)]).toEqual([ + SIDE_TAB, + { index: 2, pathname: THREAD, tab: SIDE_TAB }, + ]); + + await press(A); + await press(B); + expect([at(router), router.history.location.hash]).toEqual([ + { index: 4, pathname: THREAD, tab: B }, + "", + ]); + + await back(router); + expect(shown()).toBe(A); + await back(router); + expect([shown(), at(router).index, router.history.location.hash]).toEqual([ + SIDE_TAB, + 2, + `#${hash}`, + ]); + await back(router); + expect([shown(), at(router).index]).toEqual([PRIMARY_CHAT, 1]); + await forward(router); + expect([shown(), at(router).index, router.history.length]).toEqual([SIDE_TAB, 2, 5]); + }); + + it("retags a quote entry for a reply tab it reveals", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + const hash = quoteHash(ref.threadId); + const reply = replyTabId(ref, "assistant-1"); + router.history.push(`${THREAD}#${hash}`, { assistantCitationActivation: "quote-1" }); + const restoreView = publishWorkAreaView({ narrow: true, size: null }); + change({ type: "open-reply", thread: ref, first: "assistant-1", reveal: "quote" }); + restoreView(); + await settle(); + expect([shown(), at(router), router.history.location.hash]).toEqual([ + reply, + { index: 2, pathname: THREAD, tab: reply }, + `#${hash}`, + ]); + + await press(A); + await back(router); + expect([shown(), at(router).index, router.history.length]).toEqual([reply, 2, 4]); + }); + + it("pushes a switch to the cited side-chat tab made after input", async () => { + store().openThread(ref, SIDE); + store().activateSurface(ref, A); + const router = threadRouter([OTHER, `${THREAD}#${quoteHash(SIDE)}`]); + using _watch = watching(router); + expect(at(router)).toEqual({ index: 1, pathname: THREAD, tab: A }); + + await press(SIDE_TAB); + expect(at(router)).toEqual({ index: 2, pathname: THREAD, tab: SIDE_TAB }); + await back(router); + expect([shown(), at(router).index]).toEqual([A, 1]); + }); + + it("pushes a change made on a main-chat quote", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + const hash = quoteHash(ref.threadId); + router.history.push(`${THREAD}#${hash}`, { assistantCitationActivation: "quote-1" }); + await press(A); + expect([at(router), router.history.location.hash]).toEqual([ + { index: 3, pathname: THREAD, tab: A }, + "", + ]); + + await back(router); + expect([shown(), at(router).index, router.history.location.hash]).toEqual([ + PRIMARY_CHAT, + 2, + `#${hash}`, + ]); + }); + + it("leaves Back onto a quote entry whose tab was closed to the quote", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + router.history.push(`${THREAD}#${quoteHash(SIDE)}`, { assistantCitationActivation: "quote-1" }); + await revealSideChat(); + await press(A); + store().closeSurface(ref, SIDE_TAB); + await settle(); + + await back(router); + expect([shown(), at(router)]).toEqual([A, { index: 2, pathname: THREAD, tab: SIDE_TAB }]); + // The quote's own reveal runs again here, and it only retags the entry. + await revealSideChat(); + expect([shown(), at(router).index, router.history.length]).toEqual([SIDE_TAB, 2, 4]); + }); + + it.each([{ narrow: true }, { narrow: false }])( + "steps Back from a main-chat quote to the entry before it, narrow $narrow", + async ({ narrow }) => { + const router = threadRouter([OTHER, THREAD]); + // A narrow visit tags the entry before the quote. + watching(router)[Symbol.dispose](); + using _watch = watching(router, { narrow }); + router.history.push(`${THREAD}#${quoteHash(ref.threadId)}`, { + assistantCitationActivation: "quote-1", + }); + await settle(); + + await back(router); + expect([shown(), at(router)]).toEqual([ + PRIMARY_CHAT, + { index: 1, pathname: THREAD, tab: "chat" }, + ]); + }, + ); + + it("keeps the key of a quote entry opened without an activation", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + router.history.push(`${THREAD}#${quoteHash(SIDE)}`); + const { __TSR_key: key } = router.history.location.state; + await revealSideChat(); + expect(router.history.location.state.__TSR_key).toBe(key); + + await press(A); + await back(router); + expect([shown(), router.history.location.state.__TSR_key]).toEqual([SIDE_TAB, key]); + }); + + it("steps Back from a first side-chat quote to the tab shown before it", async () => { + store().activateSurface(ref, A); + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + router.history.push(`${THREAD}#${quoteHash(SIDE)}`, { assistantCitationActivation: "quote-1" }); + await revealSideChat(); + + await back(router); + expect([shown(), at(router)]).toEqual([A, { index: 1, pathname: THREAD, tab: A }]); + }); + + it("Back passes all three entries of a deleted thread in one press", async () => { + tags = tabHistoryTags; + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router); + await press(A); + await press(B); + } + markTabHistoryThreadDeleted(ref); + router.history.push(THIRD); + expect(at(router).index).toBe(4); + + await back(router); + expect(at(router)).toEqual({ index: 0, pathname: OTHER, tab: null }); + }); + + it("drops a pending push when the thread changes", async () => { + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router); + store().activateSurface(ref, A); + } + await settle(); + expect(router.history.length).toBe(2); + + using _watch = watching(router); + store().activateSurface(ref, B); + router.history.push(OTHER); + await settle(); + expect(at(router)).toEqual({ index: 2, pathname: OTHER, tab: null }); + }); + + it("pushes nothing on a draft route", async () => { + const router = threadRouter([OTHER, "/draft/draft-1"]); + using _watch = watching(router); + await press(A); + expect(router.history.length).toBe(2); + }); + + it("pushes under the whiteboard build's basepath", async () => { + const router = threadRouter([`/chat${OTHER}`, `/chat${THREAD}`], "/chat"); + using _watch = watching(router); + await press(A); + expect(at(router)).toEqual({ index: 2, pathname: `/chat${THREAD}`, tab: A }); + + await back(router); + expect([shown(), at(router).tab]).toEqual([PRIMARY_CHAT, "chat"]); + }); + + it("keeps tags across a reload", async () => { + const storage = memoryStorage(); + tags = createTabTags(() => storage); + const router = threadRouter([OTHER, THREAD]); + { + using _watch = watching(router); + await press(A); + await press(B); + } + + // A reload keeps the history entries and session storage, and starts a new tag map. + tags = createTabTags(() => storage); + using _watch = watching(router); + await back(router); + expect(shown()).toBe(A); + await back(router); + expect(shown()).toBe(PRIMARY_CHAT); + }); +}); diff --git a/apps/web/src/fork/workArea/tabHistory.logic.ts b/apps/web/src/fork/workArea/tabHistory.logic.ts new file mode 100644 index 0000000000000..7ef2d8807df6e --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.logic.ts @@ -0,0 +1,193 @@ +import type { ThreadRightPanelState } from "~/rightPanelStore"; + +import { + asTabId, + DEFAULT_LAYOUT, + focusedTab, + paneHolding, + resolveLayout, + type TabId, + type WorkAreaLayout, +} from "./workArea.logic"; + +/** + * Thread and tab recorded for a router history entry by its entry key. Marks `pushed` on entries + * this code pushed and `dead` on entries of a deleted thread. + */ +export type TabEntry = { + readonly thread: string; + readonly tab: TabId; + readonly pushed?: true; + readonly dead?: true; +}; + +/** Parses a valid `TabEntry` from an untrusted stored value, or returns `null`. */ +export function readTabEntry(value: unknown): TabEntry | null { + if (typeof value !== "object" || value === null || !("thread" in value) || !("tab" in value)) { + return null; + } + const pushed = "pushed" in value ? value.pushed : undefined; + const dead = "dead" in value ? value.dead : undefined; + if ( + typeof value.thread !== "string" || + typeof value.tab !== "string" || + (pushed !== undefined && pushed !== true) || + (dead !== undefined && dead !== true) + ) { + return null; + } + return { + thread: value.thread, + tab: asTabId(value.tab), + ...(pushed ? { pushed } : {}), + ...(dead ? { dead } : {}), + }; +} + +/** Returns the resolved work-area layout for `thread`, or `DEFAULT_LAYOUT` when absent. */ +export function layoutOf( + byThreadKey: Readonly>, + thread: string, +): WorkAreaLayout { + const record = byThreadKey[thread]; + return record ? resolveLayout(record) : DEFAULT_LAYOUT; +} + +/** Snapshot of right-panel state and per-thread user-action and close revision counters. */ +export type PanelRevisions = { + readonly byThreadKey: Readonly>; + readonly userActionRevisionByThreadKey: Readonly>; + readonly closeRevisionByThreadKey: Readonly>; +}; + +/** Shown tab before and after a user-driven tab change in one thread. */ +export type TabChange = { readonly from: TabId; readonly to: TabId }; + +/** + * Returns `{ from, to }` for a user-driven tab open or switch in `thread`, or `null` for closes, + * thread removals, non-user updates, or updates that keep the same shown tab. + */ +export function userShownTabChange( + prev: PanelRevisions, + next: PanelRevisions, + thread: string, +): TabChange | null { + if ( + prev.byThreadKey[thread] === next.byThreadKey[thread] || + // Only a raised count is a user action; a deleted thread loses its count. + (next.userActionRevisionByThreadKey[thread] ?? 0) <= + (prev.userActionRevisionByThreadKey[thread] ?? 0) || + prev.closeRevisionByThreadKey[thread] !== next.closeRevisionByThreadKey[thread] + ) { + return null; + } + const from = focusedTab(layoutOf(prev.byThreadKey, thread)); + const to = focusedTab(layoutOf(next.byThreadKey, thread)); + return from === to ? null : { from, to }; +} + +/** + * Current history entry's stored `tag` and whether the pending change is a quote entry's own + * reveal. + */ +export type CurrentEntry = { readonly tag: TabEntry | null; readonly reveal: boolean }; + +/** Planned tag and history writes to push a new entry or retag the current entry. */ +export type TabWrite = + | { readonly type: "push"; readonly retag: TabEntry | null; readonly push: TabEntry } + | { readonly type: "retag"; readonly retag: TabEntry }; + +/** + * Plans tag and history writes for moving from `from` to `to` in `thread`, or returns `null` + * when they match. A `current.reveal` move retags the current entry only. Any other move retags + * it to `from` if needed and pushes a `pushed` entry for `to`. + */ +export function planPush( + current: CurrentEntry, + thread: string, + { from, to }: TabChange, +): TabWrite | null { + if (from === to) return null; + const { tag } = current; + // A retag keeps the mark of an entry this code pushed. + const retagged = (tab: TabId): TabEntry => + tag?.thread === thread && tag.pushed ? { thread, tab, pushed: true } : { thread, tab }; + // A quote entry owns its own reveal; every other change gets an entry of its own. + if (current.reveal) return { type: "retag", retag: retagged(to) }; + const retag = tag?.thread === thread && tag.tab === from ? null : retagged(from); + return { type: "push", retag, push: { thread, tab: to, pushed: true } }; +} + +/** Target entry tag and URL comparison flags for a narrow-mode Back or Forward step. */ +export type Move = { + readonly entry: TabEntry | null; + readonly samePath: boolean; + readonly sameHref: boolean; + readonly moved: boolean; +}; + +/** Thread key and resolved work-area layout currently shown in narrow mode. */ +export type Shown = { + readonly thread: string; + readonly layout: WorkAreaLayout; +}; + +/** Action for a narrow-mode Back or Forward step to show a tab, skip the entry, or do nothing. */ +export type MoveDecision = + | { readonly type: "none" } + | { readonly type: "show"; readonly tab: TabId } + | { readonly type: "skip" }; + +/** + * Decides what narrow-mode Back or Forward should do for `move`. Returns `show` for another open + * tab of `shown.thread`, `skip` for a closed or already-shown tab at the same URL, and `none` + * for dead entries, different URLs, or other moves. + */ +export function decideMove(move: Move, shown: Shown): MoveDecision { + const { entry } = move; + // Deleted threads' entries are skipped once per history, outside any thread's watcher. + if (!move.moved || entry?.dead) return { type: "none" }; + if (entry === null || entry.thread !== shown.thread || !move.samePath) return { type: "none" }; + if (paneHolding(shown.layout.root, entry.tab) && focusedTab(shown.layout) !== entry.tab) { + return { type: "show", tab: entry.tab }; + } + // An entry whose URL differs, such as a quote link's, shows its own change. + return move.sameHref ? { type: "skip" } : { type: "none" }; +} + +/** Back or Forward move inspected by the per-history listener, including the chain origin tag. */ +export type HistoryMove = Pick & { + // The tag of the entry the user's Back started from, until that Back passes a base. + readonly origin: TabEntry | null; +}; + +/** Skip result from `decideHistoryMove`, distinguishing normal skips from a wide base skip. */ +export type HistorySkip = "none" | "skip" | "skip-base"; + +/** + * Decides whether the per-history listener should skip `move`. Returns `"skip"` for a dead entry + * in either mode or a `pushed` entry in wide mode, `"skip-base"` in wide mode for the base entry + * of a Back started on a `pushed` entry, and `"none"` otherwise. + */ +export function decideHistoryMove(move: HistoryMove, wide: boolean): HistorySkip { + const { entry, origin } = move; + if (!move.moved) return "none"; + if (entry?.dead) return "skip"; + if (!wide) return "none"; + // Wide windows step as if the pushed entries were not there. + if (entry?.pushed) return "skip"; + // A Back that started inside a run of pushed entries logically started at that run's base. + const base = + origin?.pushed === true && move.samePath && (entry === null || entry.thread === origin.thread); + return base ? "skip-base" : "none"; +} + +// A Back or Forward between two entries of one thread, as our restores and skips are. +/** + * Returns `true` when `move` stepped along the same pathname between two entries of `left`'s + * thread. + */ +export const isTabStep = ( + move: Pick, + left: TabEntry | null, +) => move.moved && move.samePath && move.entry !== null && move.entry.thread === left?.thread; diff --git a/apps/web/src/fork/workArea/tabHistory.ts b/apps/web/src/fork/workArea/tabHistory.ts new file mode 100644 index 0000000000000..5d1c45cbcb4c1 --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.ts @@ -0,0 +1,354 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { + type AnyRouter, + type HistoryLocation, + type RouterHistory, + useRouter, +} from "@tanstack/react-router"; +import { useEffect } from "react"; + +import { useStableCallback } from "~/hooks/useStableCallback"; +import { + assistantCitationFromLocation, + withoutAssistantCitationHash, +} from "~/lib/assistantCitationNavigation"; +import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "~/rightPanelLayout"; +import { useRightPanelStore } from "~/rightPanelStore"; +import { resolveThreadRouteRef } from "~/threadRoutes"; + +import { + decideHistoryMove, + decideMove, + isTabStep, + layoutOf, + planPush, + type TabChange, + type TabEntry, + userShownTabChange, +} from "./tabHistory.logic"; +import { tabHistoryTags, type TabTags } from "./tabHistoryTags"; +import { focusedTab, type TabId } from "./workArea.logic"; + +type TabHistoryRouter = Pick & { + readonly history: RouterHistory; +}; + +const THREAD_ROUTE_ID = "/_chat/$environmentId/$threadId"; + +function threadRouteRef( + router: TabHistoryRouter, + location: HistoryLocation, +): ScopedThreadRef | null { + const { pathname } = router.parseLocation(location); + const { foundRoute, routeParams } = router.getMatchedRoutes(pathname); + return foundRoute?.id === THREAD_ROUTE_ID ? resolveThreadRouteRef(routeParams) : null; +} + +/** Marks all recorded tab-history entries for `ref` as deleted so Back and Forward skip them. */ +export const markTabHistoryThreadDeleted = (ref: ScopedThreadRef): void => + tabHistoryTags.markDead(scopedThreadKey(ref)); + +// The tag of our push in flight, until its PUSH event takes it. +let pushing: TabEntry | undefined; +let ownPushInFlight = false; +// Our consecutive pushes on one history: the entry before them, each entry they pushed, and the last. +let ownRun: { + readonly history: RouterHistory; + readonly passed: Set; + latest: HistoryLocation; +} | null = null; +// The location of the latest history event, when it was one of our pushes or a same-thread step. +let lastTabStep: HistoryLocation | null = null; + +/** + * Returns `true` when an own tab push is in flight or only consecutive tab pushes by this code + * changed history since `base`. + */ +export const onlyOwnTabPushesSince = (base: HistoryLocation): boolean => + ownPushInFlight || + (ownRun !== null && ownRun.history.location === ownRun.latest && ownRun.passed.has(base)); + +// Upstream test doubles of the router history send events without a location. +/** + * Returns `true` when an own tab push is in flight or `location` came from this code's tab push + * or a same-thread Back or Forward step. + */ +export const isWorkAreaTabStep = (location: HistoryLocation | undefined): boolean => + ownPushInFlight || (location !== undefined && location === lastTabStep); + +type Step = "BACK" | "FORWARD"; +type HistoryHub = { + readonly push: (href: string, tag: TabEntry) => void; + readonly skip: (step: Step) => void; + readonly noteModalClose: (href: string) => void; +}; + +const hubs = new WeakMap(); + +// One listener per history, installed with the router and never removed, so it runs before any +// listener that reads our tags or the helpers above. It classifies every event, tags our pushes +// in their own notify, and makes the moves no thread view can: skips over a deleted thread's and +// a wide window's tab entries, and the push that ends a Settings or Usage Close. +function hubFor(router: TabHistoryRouter, tags: TabTags, isWide: () => boolean): HistoryHub { + const { history } = router; + const known = hubs.get(history); + if (known !== undefined) return known; + let previous = history.location; + let pendingSkip: (() => void) | undefined; + // Our pending skip, and the tag the user's Back started from while that Back has a base ahead. + let chain: { readonly step: Step; readonly origin: TabEntry | null } | null = null; + // The page a Settings or Usage Close returns to, until the next history event. + let modalReturn: string | null = null; + const push = (href: string, tag: TabEntry) => { + pushing = tag; + ownPushInFlight = true; + try { + history.push(href); + // Commit now so a replace later in this tick cannot fold into the push. + history.flush(); + } finally { + // A blocker can defer the push; its PUSH event then gets only the eager tag. + pushing = undefined; + ownPushInFlight = false; + } + }; + // The Close goes back to the entry before the page it returns to and navigates there again, + // which the router skips when that entry has the same URL. A fresh entry here drops the modal + // from Forward history in its place. + const pushModalReturn = (location: HistoryLocation, href: string) => { + const ref = threadRouteRef(router, location); + const landed = withoutAssistantCitationHash(router.parseLocation(location).href); + if (ref === null || landed !== href) return; + const thread = scopedThreadKey(ref); + const tab = focusedTab(layoutOf(useRightPanelStore.getState().byThreadKey, thread)); + // Marked as ours in both widths, so one wide Back still passes it and the run before it. + push(withoutAssistantCitationHash(location.href), { thread, tab, pushed: true }); + }; + const skip = (step: Step, origin: TabEntry | null = null) => { + const go = step === "BACK" ? () => history.back() : () => history.forward(); + chain = { step, origin }; + pendingSkip = go; + // A microtask runs before the router renders a missing thread and redirects. Memory + // history notifies inside back(), so stepping right here would re-enter the listeners. + queueMicrotask(() => { + if (pendingSkip !== go) return; + pendingSkip = undefined; + go(); + }); + }; + history.subscribe(({ location, action }) => { + pendingSkip = undefined; + const before = previous; + previous = location; + const ownSkip = chain?.step === action.type ? chain : null; + chain = null; + lastTabStep = null; + const closing = modalReturn; + modalReturn = null; + if (action.type === "PUSH" && pushing !== undefined) { + tags.set(location.state, pushing); + pushing = undefined; + const run = + ownRun?.history === history + ? ownRun + : { history, passed: new Set([before]), latest: location }; + run.passed.add(location); + run.latest = location; + ownRun = run; + lastTabStep = location; + return; + } + if (ownRun?.history === history) ownRun = null; + if (action.type === "GO" && closing !== null) pushModalReturn(location, closing); + if (action.type !== "BACK" && action.type !== "FORWARD") return; + const left = tags.get(before.state); + const move = { + entry: tags.get(location.state), + samePath: before.pathname === location.pathname, + moved: before.state.__TSR_index !== location.state.__TSR_index, + // A user's own Back starts a new chain; Forward never passes a base. + origin: action.type === "BACK" ? (ownSkip === null ? left : ownSkip.origin) : null, + }; + if (isTabStep(move, left)) lastTabStep = location; + const decision = decideHistoryMove(move, isWide()); + if (decision !== "none") skip(action.type, decision === "skip" ? move.origin : null); + }); + const hub: HistoryHub = { + push, + skip, + noteModalClose: (href) => { + modalReturn = href; + }, + }; + hubs.set(history, hub); + return hub; +} + +const INPUT_EVENTS = ["pointerdown", "keydown", "touchstart"] as const; + +const windowIsWide = () => !window.matchMedia(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY).matches; + +/** + * Installs the one per-history listener on `router.history` (no-op if already installed). + * It tags this code's pushes, skips dead entries in both widths, skips pushed entries and at most + * one base per Back in wide mode, and pushes a fresh `pushed` entry on a marked modal Close. + */ +export const installTabHistoryHub = (router: TabHistoryRouter): void => + void hubFor(router, tabHistoryTags, windowIsWide); + +/** + * Marks the next history event on `history` as a Settings or Usage Close returning to `href`. + * If that event is a `GO` landing on a matching thread route, the listener pushes a fresh + * hashless `pushed` entry for the shown tab in both widths; any event clears the mark. + */ +export const noteAppModalClose = (history: RouterHistory, href: string): void => + hubs.get(history)?.noteModalClose(href); + +/** + * Ensures the per-history listener exists (using `deps.tags` and `deps.isWide` if not yet + * installed) and returns a stop function. In narrow mode it tags entries of `thread`, pushes user + * tab changes, and restores open tabs or skips closed or already-shown same-URL entries. + */ +export function watchTabHistory(deps: { + readonly router: TabHistoryRouter; + readonly thread: string; + readonly narrow: boolean; + readonly activate: (tab: TabId) => void; + readonly tags: TabTags; + readonly input: EventTarget | undefined; + readonly isWide: () => boolean; +}): () => void { + const { router, thread, narrow, activate, tags, input } = deps; + const { history } = router; + const hub = hubFor(router, tags, deps.isWide); + // A wide window steps as if no tab entry existed, which the history's own listener handles. + if (!narrow) return () => {}; + const layout = () => layoutOf(useRightPanelStore.getState().byThreadKey, thread); + const shownTab = () => focusedTab(layout()); + const showsThread = () => { + const ref = threadRouteRef(router, history.location); + return ref !== null && scopedThreadKey(ref) === thread; + }; + let previous = history.location; + let restoring = false; + // A change on a quote entry with no pointer, key or touch input since the entry was reached is + // the quote's own reveal. + let inputSinceArrival = false; + let pending: { change: TabChange; reveal: boolean; timer: ReturnType } | null = + null; + + const cancelPush = () => { + if (pending !== null) clearTimeout(pending.timer); + pending = null; + }; + + // Entries pushed by the router or by anyone else record the tab shown when they are reached. + const tagShown = () => { + if (!showsThread()) return; + const { state } = history.location; + if (tags.get(state)?.thread !== thread) tags.set(state, { thread, tab: shownTab() }); + }; + + const write = () => { + if (pending === null) return; + const { change, reveal } = pending; + pending = null; + if (!showsThread()) return; + const { href, state } = history.location; + const current = { + tag: tags.get(state), + reveal: reveal && assistantCitationFromLocation(href) !== null, + }; + const plan = planPush(current, thread, change); + if (plan === null) return; + if (plan.retag !== null) tags.set(state, plan.retag); + // A copy of the quote hash would run the quote's reveal again on Back or Forward. + if (plan.type === "push") hub.push(withoutAssistantCitationHash(href), plan.push); + }; + + const stopStore = useRightPanelStore.subscribe((next, prev) => { + if (restoring) return; + const change = userShownTabChange(prev, next, thread); + if (change === null) return; + // The entry records the tab the user chose, even if a reveal shows another before it is written. + if (pending !== null) { + pending.change = { from: pending.change.from, to: change.to }; + return; + } + // A task, not a microtask, so the store writes of one gesture make one entry. + pending = { change, reveal: !inputSinceArrival, timer: setTimeout(write, 0) }; + }); + + const noteInput = () => { + inputSinceArrival = true; + }; + for (const type of INPUT_EVENTS) { + input?.addEventListener(type, noteInput, { capture: true, passive: true }); + } + + const stopHistory = history.subscribe(({ location, action }) => { + const before = previous; + previous = location; + inputSinceArrival = false; + if (action.type === "BACK" || action.type === "FORWARD") { + cancelPush(); + const move = { + entry: tags.get(location.state), + samePath: before.pathname === location.pathname, + sameHref: before.href === location.href, + moved: before.state.__TSR_index !== location.state.__TSR_index, + }; + const decision = decideMove(move, { thread, layout: layout() }); + if (decision.type === "show") { + restoring = true; + try { + activate(decision.tab); + } finally { + restoring = false; + } + } else if (decision.type === "skip") { + hub.skip(action.type); + } + } + tagShown(); + }); + + tagShown(); + + return () => { + cancelPush(); + for (const type of INPUT_EVENTS) input?.removeEventListener(type, noteInput, { capture: true }); + stopStore(); + stopHistory(); + }; +} + +/** + * Runs narrow-mode tab-history tracking for `threadRef` and calls `activate` when Back or Forward + * shows a tab. The router's per-history listener handles dead-entry skips in both widths, wide + * skips of pushed entries and one base per Back, and marked modal-Close pushes. + */ +export function useTabHistory( + threadRef: ScopedThreadRef, + narrow: boolean, + activate: (tab: TabId) => void, +): void { + const router = useRouter(); + const thread = scopedThreadKey(threadRef); + const show = useStableCallback(activate); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- browser Back and Forward arrive as history events outside React + useEffect( + () => + watchTabHistory({ + router, + thread, + narrow, + activate: show, + tags: tabHistoryTags, + input: window, + isWide: windowIsWide, + }), + [router, thread, narrow, show], + ); +} diff --git a/apps/web/src/fork/workArea/tabHistoryTags.ts b/apps/web/src/fork/workArea/tabHistoryTags.ts new file mode 100644 index 0000000000000..feaad59d73f91 --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistoryTags.ts @@ -0,0 +1,82 @@ +import type { HistoryLocation } from "@tanstack/react-router"; + +import { readTabEntry, type TabEntry } from "./tabHistory.logic"; + +const STORAGE_KEY = "t3code:work-area-tab-history:v1"; +const MAX_TAGS = 500; + +type EntryState = HistoryLocation["state"]; +type TagStorage = Pick; + +/** Map from a router history entry's state key to its recorded `TabEntry`. */ +export type TabTags = { + readonly get: (state: EntryState) => TabEntry | null; + readonly set: (state: EntryState, tag: TabEntry) => void; + /** Marks every recorded entry of `thread` as `dead` and saves the map. */ + readonly markDead: (thread: string) => void; +}; + +const entryKey = (state: EntryState) => state.__TSR_key ?? state.key; + +function readStored(storage: () => TagStorage | undefined): Map { + const tags = new Map(); + try { + const rows: unknown = JSON.parse(storage()?.getItem(STORAGE_KEY) ?? "[]"); + if (!Array.isArray(rows)) return tags; + for (const row of rows) { + if (!Array.isArray(row) || typeof row[0] !== "string") continue; + const tag = readTabEntry(row[1]); + if (tag !== null) tags.set(row[0], tag); + } + } catch { + // Blocked or corrupted storage starts with no tags. + } + return tags; +} + +/** + * Creates a `TabTags` map backed by `storage`, keeping the newest 500 entries across reloads. + * Ignores blocked or corrupted storage and falls back to memory for the current page load. + */ +export function createTabTags(storage: () => TagStorage | undefined): TabTags { + const tags = readStored(storage); + const save = () => { + try { + storage()?.setItem(STORAGE_KEY, JSON.stringify([...tags])); + } catch { + // Full or blocked storage keeps the tags for this page load only. + } + }; + return { + get: (state) => { + const key = entryKey(state); + return key === undefined ? null : (tags.get(key) ?? null); + }, + set: (state, tag) => { + const key = entryKey(state); + if (key === undefined) return; + tags.delete(key); + tags.set(key, tag); + for (const oldest of tags.keys()) { + if (tags.size <= MAX_TAGS) break; + tags.delete(oldest); + } + save(); + }, + markDead: (thread) => { + let changed = false; + for (const [key, tag] of tags) { + if (tag.thread !== thread || tag.dead) continue; + tags.set(key, { ...tag, dead: true }); + changed = true; + } + if (changed) save(); + }, + }; +} + +// Session storage lasts as long as this tab's history entries, across reloads. +/** Shared `TabTags` map backed by `window.sessionStorage` when running in a browser. */ +export const tabHistoryTags = createTabTags(() => + typeof window === "undefined" ? undefined : window.sessionStorage, +); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 2a591127044d1..5aa06b864f178 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -54,6 +54,7 @@ import { useDiffPanelStore } from "../diffPanelStore"; import { usePreviewMiniPlayerStore } from "../previewMiniPlayerStore"; import { clearThreadPreviewState } from "../previewStateStore"; import { useRightPanelStore } from "../rightPanelStore"; +import { isWorkAreaTabStep, markTabHistoryThreadDeleted } from "../fork/workArea/tabHistory"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes"; import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup"; @@ -269,6 +270,7 @@ function expireThreadUndos(target: ScopedThreadRef, kinds: readonly string[]) { function clearDeletedThreadPanelState(ref: ScopedThreadRef) { clearThreadPreviewState(ref); useRightPanelStore.getState().removeThread(ref); + markTabHistoryThreadDeleted(ref); useDiffPanelStore.getState().removeThread(ref); usePreviewMiniPlayerStore.getState().removeThread(ref); } @@ -501,6 +503,7 @@ export function useThreadActions() { ]) { releaseComposerDraftUploads(ref); clearComposerDraftForThread(ref); + markTabHistoryThreadDeleted(ref); } expireThreadUndos(target, [...LIST_PLACEMENT_UNDO_KINDS, "archive"]); refreshArchivedThreadsForEnvironment(target.environmentId); @@ -623,9 +626,10 @@ export function useThreadActions() { }); let navigatedDuringDelete = false; // The missing-thread redirect and the index draft replace this entry; any other history - // action while the delete is pending is the user's own choice, which must win. - const stopWatchingHistory = router.history.subscribe(({ action }) => { - if (action.type !== "REPLACE") navigatedDuringDelete = true; + // action while the delete is pending, other than a work-area tab step, is the user's own + // choice, which must win. + const stopWatchingHistory = router.history.subscribe(({ action, location }) => { + if (action.type !== "REPLACE" && !isWorkAreaTabStep(location)) navigatedDuringDelete = true; }); const deleteResult = await deleteThreadMutation({ environmentId: threadRef.environmentId, @@ -646,6 +650,7 @@ export function useThreadActions() { const sideChatRef = scopeThreadRef(threadRef.environmentId, entry.id); releaseComposerDraftUploads(sideChatRef); clearComposerDraftForThread(sideChatRef); + markTabHistoryThreadDeleted(sideChatRef); } clearProjectDraftThreadById( scopeProjectRef(threadRef.environmentId, thread.projectId), diff --git a/apps/web/src/router.ts b/apps/web/src/router.ts index 369a68b64ba3f..d2788adf349fb 100644 --- a/apps/web/src/router.ts +++ b/apps/web/src/router.ts @@ -1,16 +1,19 @@ import { createRouter, RouterHistory } from "@tanstack/react-router"; import { isWhiteboardBuild, WHITEBOARD_ROUTER_BASEPATH } from "./fork/whiteboard/build"; +import { installTabHistoryHub } from "./fork/workArea/tabHistory"; import { routeTree } from "./routeTree.gen"; export function getRouter(history: RouterHistory) { - return createRouter({ + const router = createRouter({ routeTree, history, ...(isWhiteboardBuild ? { basepath: WHITEBOARD_ROUTER_BASEPATH } : {}), context: {}, defaultPreload: "intent", }); + installTabHistoryHub(router); + return router; } export type AppRouter = ReturnType;