From b3f8ff2ff7ac7579596881f58cbb7e5427da2a5c 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 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 deleted threads, and leaves the thread after the starting tab. Entries the app adds itself are tagged when reached, quote links keep their own reveal, and Reopen Closed View adds no entry. Wide windows push nothing and skip leftover same-URL tab entries. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- apps/web/src/fork/workArea/WorkArea.tsx | 2 + .../fork/workArea/tabHistory.browser.test.tsx | 298 +++++++ .../fork/workArea/tabHistory.logic.test.ts | 739 ++++++++++++++++++ .../web/src/fork/workArea/tabHistory.logic.ts | 124 +++ apps/web/src/fork/workArea/tabHistory.ts | 186 +++++ apps/web/src/fork/workArea/tabHistoryTags.ts | 68 ++ apps/web/src/fork/workArea/useThreadGone.ts | 18 +- 8 files changed, 1434 insertions(+), 3 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 5372ae1d18a67..d33cc6d1d035d 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/fork/workArea/WorkArea.tsx b/apps/web/src/fork/workArea/WorkArea.tsx index 7ef3e33c85521..6f7c329010a63 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..1b8670d27b5ed --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.browser.test.tsx @@ -0,0 +1,298 @@ +import "~/index.css"; + +import { createBrowserHistory } from "@tanstack/react-router"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { MessageId, 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 { __setClientSettingsForTests } from "~/hooks/useSettings"; +import { assistantCitationNavigation } from "~/lib/assistantCitationNavigation"; +import { getRouter } from "~/router"; +import { useRightPanelStore } from "~/rightPanelStore"; +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"; + +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 owner = scopeThreadRef(ENVIRONMENT_ID, ownerThread.id); +const OWNER_PATH = `/${ENVIRONMENT_ID}/${ownerThread.id}`; +const OTHER_PATH = `/${ENVIRONMENT_ID}/${otherThread.id}`; +const deleted = scopeThreadRef(ENVIRONMENT_ID, ThreadId.make("deleted")); + +function setup() { + useRightPanelStore.setState({ + byThreadKey: { + [scopedThreadKey(owner)]: 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", + }); +} + +const shownTab = () => + focusedTab(resolveLayout(useRightPanelStore.getState().byThreadKey[scopedThreadKey(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 deletedEntry?: boolean } = {}) { + await page.viewport(width, 900); + const startHref = window.location.href; + window.history.pushState(null, "", OTHER_PATH); + const history = createBrowserHistory(); + if (options.deletedEntry) { + // An entry recorded in narrow mode on a thread deleted since. + history.push(`/${deleted.environmentId}/${deleted.threadId}`); + history.flush(); + tabHistoryTags.set(history.location.state, { + thread: scopedThreadKey(deleted), + tab: asTabId("chat"), + }); + } + history.push(OWNER_PATH); + history.flush(); + const router = getRouter(history); + await router.load(); + await using stack = new AsyncDisposableStack(); + stack.defer(() => { + history.destroy(); + window.history.replaceState(null, "", startHref); + }); + // AppRoot brings its own router. + stack.use(await render(, { router: false })); + await expect + .element(page.getByRole("textbox", { name: `Message ${ownerThread.title}` })) + .toBeVisible(); + const opened = stack.move(); + return { router, [Symbol.asyncDispose]: () => opened.disposeAsync() }; +} + +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; + +describe("tab history", () => { + it("steps Back through narrow tab presses, skips a closed tab, then leaves the thread", async () => { + using _environment = installFakeEnvironment([ownerThread, otherThread]); + 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(page.getByRole("textbox", { name: `Message ${otherThread.title}` })) + .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([ownerThread, otherThread]); + 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(page.getByRole("textbox", { name: `Message ${otherThread.title}` })) + .toBeVisible(); + expect(app.router.state.location.pathname).toBe(OTHER_PATH); + expect([historyIndex(), window.history.length]).toEqual([0, length]); + }); + + it("pushes tab presses made on a main-chat quote, and Back steps through the quote", async () => { + using _environment = installFakeEnvironment([ownerThread, otherThread]); + setup(); + await using app = await openOwner(800); + const quoted = () => window.location.hash.startsWith("#assistant-citation="); + await app.router.navigate( + assistantCitationNavigation( + { + version: 1, + environmentId: ENVIRONMENT_ID, + threadId: ownerThread.id, + messageId: MessageId.make(`${ownerThread.id}-assistant-0`), + text: "Answer", + start: 0, + end: 6, + prefix: "", + suffix: "", + }, + null, + ), + ); + 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.each([1400, 800])( + "lets a queued reopen follow its browser restore to the other thread at width %i", + async (width) => { + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + using _environment = installFakeEnvironment([ownerThread, otherThread]); + const other = scopeThreadRef(ENVIRONMENT_ID, otherThread.id); + 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; + using _preview = answerRpc(WS_METHODS.previewOpen, () => { + requested = true; + return Effect.promise(() => response.promise); + }); + setup(); + await using app = await openOwner(width); + useRightPanelStore.getState().closeSurface(owner, "diff"); + useClosedViewStore.setState({ entries: [] }); + const closed = useClosedViewStore.getState(); + closed.remember({ kind: "browser", threadRef: other, snapshot: closedBrowser }); + closed.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. + for (const _press of [1, 2]) { + const key = new KeyboardEvent("keydown", { + key: "T", + ctrlKey: true, + shiftKey: true, + bubbles: true, + cancelable: true, + }); + document.body.dispatchEvent(key); + expect(key.defaultPrevented).toBe(true); + } + await expect.poll(() => requested).toBe(true); + await expect.poll(shownTab).toBe("diff"); + expect(historyIndex()).toBe(1); + + response.resolve({ ...closedBrowser, tabId: "restored-tab" }); + await expect.poll(() => app.router.history.location.pathname).toBe(OTHER_PATH); + const otherPanel = useRightPanelStore.getState().byThreadKey[scopedThreadKey(other)]; + expect(otherPanel?.surfaces.some((surface) => surface.id === "browser:restored-tab")).toBe( + true, + ); + }, + ); + + it("Back passes the recorded entries of a deleted thread", async () => { + using _environment = installFakeEnvironment([ownerThread, otherThread]); + setup(); + await using app = await openOwner(800, { deletedEntry: true }); + expect(historyIndex()).toBe(2); + + window.history.back(); + await expect + .element(page.getByRole("textbox", { name: `Message ${otherThread.title}` })) + .toBeVisible(); + expect([historyIndex(), app.router.state.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..520e7309cf3e3 --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.logic.test.ts @@ -0,0 +1,739 @@ +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { MessageId, type ScopedThreadRef, 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 { useClosedViewStore } from "~/closedViewStore"; +import { assistantCitationRoute } from "~/lib/assistantCitationNavigation"; + +import { + decideMove, + type Move, + planPush, + readTabEntry, + type Shown, + type TabEntry, + userShownTabChange, +} from "./tabHistory.logic"; +import { watchTabHistory } from "./tabHistory"; +import { createTabTags, type TabTags } from "./tabHistoryTags"; +import { asTabId, DEFAULT_LAYOUT, focusedTab, PRIMARY_CHAT } from "./workArea.logic"; +import { + change, + env, + layout, + onePane, + other, + ref, + resetWorkAreaStore, + store, +} 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 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 }, + ])("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")]); + }); + + 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, citedTab: null }); + it.each([ + { + name: "retags an untagged entry with the tab left", + current: plain(null), + plan: { type: "push", retag: entry("chat"), push: entry(A) }, + }, + { + name: "keeps an entry that already names the tab left", + current: plain(entry("chat")), + plan: { type: "push", retag: null, push: entry(A) }, + }, + { + name: "retags a stale entry", + current: plain(entry(B)), + plan: { type: "push", retag: entry("chat"), push: entry(A) }, + }, + { + name: "retags another thread's entry", + current: plain(entry("chat", "env-1:thread-other")), + plan: { type: "push", retag: entry("chat"), push: entry(A) }, + }, + { + name: "retags a quote entry for the tab it cites", + current: { tag: entry("chat"), citedTab: A }, + plan: { type: "retag", retag: entry(A) }, + }, + { + name: "pushes a change from a quote entry to a tab it does not cite", + current: { tag: entry("chat"), citedTab: B }, + plan: { type: "push", retag: null, push: entry(A) }, + }, + ])("$name", ({ current, plan }) => { + expect(planPush(current, KEY, PRIMARY_CHAT, A)).toEqual(plan); + }); + + it("writes nothing when the shown tab came back", () => { + expect(planPush(plain(null), KEY, A, A)).toBeNull(); + expect(planPush({ tag: null, citedTab: A }, KEY, A, 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, + gone: false, + ...over, + }); + const goneThreadEntry = move({ + entry: entry(A, "env-1:thread-gone"), + samePath: false, + sameHref: false, + gone: 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: "skips a closed tab on an entry with another URL", + move: move({ entry: entry(C), sameHref: false }), + decision: { type: "skip" }, + }, + { + 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: "skips a deleted thread's entry", move: goneThreadEntry, decision: { type: "skip" } }, + { + name: "ignores a deleted thread's entry that stayed", + move: { ...goneThreadEntry, moved: false }, + decision: { type: "none" }, + }, + ])("narrow: $name", ({ move: theMove, decision }) => { + const shown: Shown = { thread: KEY, narrow: true, layout: threeTabs() }; + expect(decideMove(theMove, shown)).toEqual(decision); + }); + + it("skips every same-thread entry with the same URL when wide", () => { + const shown: Shown = { thread: KEY, narrow: false, layout: threeTabs() }; + expect(decideMove(move(), shown)).toEqual({ type: "skip" }); + expect(decideMove(move({ samePath: false }), shown)).toEqual({ type: "none" }); + expect(decideMove(move({ sameHref: false }), shown)).toEqual({ type: "none" }); + expect(decideMove(goneThreadEntry, shown)).toEqual({ type: "skip" }); + }); + + it("reads a thread with no record as the default layout", () => { + const shown: Shown = { thread: KEY, narrow: true, layout: DEFAULT_LAYOUT }; + expect(decideMove(move({ entry: entry("chat") }), shown)).toEqual({ type: "skip" }); + }); +}); + +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 }); + expect(counted(act)).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)).toBe(PRIMARY_CHAT); + }); +}); + +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 DELETED = scopeThreadRef(env, ThreadId.make("thread-deleted")); +const DELETED_PATH = `/${DELETED.environmentId}/${DELETED.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; + beforeEach(() => { + vi.useFakeTimers(); + tags = createTabTags(() => undefined); + useClosedViewStore.setState({ entries: [] }); + // [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(); + const press = async (tab: string) => { + 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; + readonly threadGone?: (thread: ScopedThreadRef) => boolean; + } = {}, + ): Disposable => { + const stop = watchTabHistory({ + router, + thread: KEY, + narrow: options.narrow ?? true, + activate: (tab) => change({ type: "activate", tab }), + tags, + threadGone: options.threadGone ?? (() => false), + }); + 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(); + }; + + 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 }); + + 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("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("ignores the Settings close jump and pushes nothing over Settings", 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 }); + + const steps = at(router).index - returnIndex; + router.history.go(-(steps + 1)); + router.history.push(THREAD); + await settle(); + expect([shown(), at(router)]).toEqual([C, { index: 3, pathname: THREAD, tab: C }]); + + await back(router); + expect(shown()).toBe(A); + }); + + it("tags the entry the Settings close pushes, so Back and Forward step over it", 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"); + + // useCloseAppModal: back to the entry before the return entry, then push the thread again. + const steps = at(router).index - returnIndex; + router.history.go(-(steps + 1)); + router.history.push(THREAD); + await settle(); + + await back(router); + expect([shown(), at(router).index]).toEqual([A, 2]); + await forward(router); + expect([shown(), at(router).index]).toEqual([B, 3]); + }); + + 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 }); + + 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("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.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("pushes nothing for a tab a reopen restores", async () => { + const router = threadRouter([OTHER, THREAD]); + using _watch = watching(router); + const closed = useClosedViewStore.getState(); + const id = closed.remember({ + kind: "panel-tab", + threadRef: ref, + surface: { id: "diff", kind: "diff" }, + }); + + // ReopenClosedViewShortcut: the restore write, then its removal of the entry. + store().activateSurface(ref, A); + closed.remove(id); + await settle(); + expect([shown(), router.history.length]).toEqual([A, 2]); + }); + + it.each([ + { narrow: true, gone: true, index: 0 }, + { narrow: false, gone: true, index: 0 }, + { narrow: true, gone: false, index: 2 }, + ])( + "Back over a deleted thread's entries, narrow $narrow and gone $gone, reaches index $index", + async ({ narrow, gone, index }) => { + const router = threadRouter([OTHER, DELETED_PATH]); + tags.set(router.history.location.state, entry("chat", scopedThreadKey(DELETED))); + router.history.push(DELETED_PATH); + tags.set(router.history.location.state, entry(A, scopedThreadKey(DELETED))); + router.history.push(THREAD); + using _watch = watching(router, { + narrow, + threadGone: (thread) => gone && thread.threadId === DELETED.threadId, + }); + + await back(router); + expect(at(router).index).toBe(index); + }, + ); + + 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..479e2fd8a0b36 --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.logic.ts @@ -0,0 +1,124 @@ +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. */ +export type TabEntry = { readonly thread: string; readonly tab: TabId }; + +/** 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; + } + return typeof value.thread === "string" && typeof value.tab === "string" + ? { thread: value.thread, tab: asTabId(value.tab) } + : null; +} + +export function layoutOf( + byThreadKey: Readonly>, + thread: string, +): WorkAreaLayout { + const record = byThreadKey[thread]; + return record ? resolveLayout(record) : DEFAULT_LAYOUT; +} + +export type PanelRevisions = { + readonly byThreadKey: Readonly>; + readonly userActionRevisionByThreadKey: Readonly>; + readonly closeRevisionByThreadKey: Readonly>; +}; + +/** + * Returns the tab shown before a user-driven 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, +): TabId | 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)); + return from === focusedTab(layoutOf(next.byThreadKey, thread)) ? null : from; +} + +export type CurrentEntry = { readonly tag: TabEntry | null; readonly citedTab: TabId | null }; + +export type TabWrite = + | { readonly type: "push"; readonly retag: TabEntry | null; readonly push: TabEntry } + | { readonly type: "retag"; readonly retag: TabEntry }; + +/** + * Plans the tag and history writes for moving from `from` to `to` in `thread`, or returns `null` + * when they match. Moving to `current.citedTab` retags the current entry only. Any other move + * retags it to `from` if needed and pushes a new entry for `to`. + */ +export function planPush( + current: CurrentEntry, + thread: string, + from: TabId, + to: TabId, +): TabWrite | null { + if (from === to) return null; + const push = { thread, tab: to }; + // A quote entry owns its own reveal; every other change gets an entry of its own. + if (to === current.citedTab) return { type: "retag", retag: push }; + const { tag } = current; + const retag = tag?.thread === thread && tag.tab === from ? null : { thread, tab: from }; + return { type: "push", retag, push }; +} + +export type Move = { + readonly entry: TabEntry | null; + readonly samePath: boolean; + readonly sameHref: boolean; + readonly moved: boolean; + readonly gone: boolean; +}; + +export type Shown = { + readonly thread: string; + readonly narrow: boolean; + readonly layout: WorkAreaLayout; +}; + +export type MoveDecision = + | { readonly type: "none" } + | { readonly type: "show"; readonly tab: TabId } + | { readonly type: "skip" }; + +/** + * Decides what Back or Forward should do for `move`. Returns `show` for another open tab of + * `shown.thread` in narrow mode, `skip` for a deleted thread's entry, a closed tab in narrow + * mode, or a same-URL entry in wide mode or for the shown tab, and `none` otherwise. + */ +export function decideMove(move: Move, shown: Shown): MoveDecision { + const { entry } = move; + if (!move.moved || entry === null) return { type: "none" }; + if (entry.thread !== shown.thread) return move.gone ? { type: "skip" } : { type: "none" }; + if (!move.samePath) return { type: "none" }; + const open = paneHolding(shown.layout.root, entry.tab); + if (shown.narrow && open && focusedTab(shown.layout) !== entry.tab) { + return { type: "show", tab: entry.tab }; + } + if (shown.narrow && !open) return { type: "skip" }; + // An entry whose URL differs, such as a quote link's, shows its own change. + return move.sameHref ? { type: "skip" } : { type: "none" }; +} diff --git a/apps/web/src/fork/workArea/tabHistory.ts b/apps/web/src/fork/workArea/tabHistory.ts new file mode 100644 index 0000000000000..4d8300ecf60bf --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistory.ts @@ -0,0 +1,186 @@ +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 { useClosedViewStore } from "~/closedViewStore"; +import { useStableCallback } from "~/hooks/useStableCallback"; +import { + assistantCitationFromLocation, + withoutAssistantCitationHash, +} from "~/lib/assistantCitationNavigation"; +import { useRightPanelStore } from "~/rightPanelStore"; +import { resolveThreadRouteRef } from "~/threadRoutes"; + +import { decideMove, layoutOf, planPush, userShownTabChange } from "./tabHistory.logic"; +import { tabHistoryTags, type TabTags } from "./tabHistoryTags"; +import { readThreadGone } from "./useThreadGone"; +import { focusedTab, surfaceTabId, 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; +} + +/** + * Tracks `thread` tabs in `deps.tags` and router history, and returns a stop function. In narrow + * mode it tags reached entries, pushes user tab changes unless a reopen or move cancels them, + * and restores open tabs or skips closed ones. It also skips deleted-thread and 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 threadGone: (thread: ScopedThreadRef) => boolean; +}): () => void { + const { router, thread, narrow, activate, tags, threadGone } = deps; + const { history } = router; + 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; + let pendingPush: ReturnType | undefined; + let pendingSkip: (() => void) | undefined; + + const cancelPush = () => { + clearTimeout(pendingPush); + pendingPush = undefined; + }; + + // Entries pushed by the router or by anyone else record the tab shown when they are reached. + const tagShown = () => { + if (!narrow || !showsThread()) return; + const { state } = history.location; + if (tags.get(state)?.thread !== thread) tags.set(state, { thread, tab: shownTab() }); + }; + + const write = (from: TabId) => { + pendingPush = undefined; + if (!showsThread()) return; + const { href, state } = history.location; + const citation = assistantCitationFromLocation(href); + const current = { + tag: tags.get(state), + citedTab: citation === null ? null : surfaceTabId(`thread:${citation.threadId}`), + }; + const plan = planPush(current, thread, from, shownTab()); + if (plan === null) return; + if (plan.retag !== null) tags.set(state, plan.retag); + if (plan.type === "push") { + // A copy of the quote hash would run the quote's reveal again on Back or Forward. + history.push(withoutAssistantCitationHash(href)); + // Commit now so a replace later in this tick cannot fold into the push. + history.flush(); + // A blocker can defer the push; the PUSH event then tags the entry. + if (history.location.state !== state) tags.set(history.location.state, plan.push); + } + }; + + const stopStore = useRightPanelStore.subscribe((next, prev) => { + if (!narrow || restoring || pendingPush !== undefined) return; + const from = userShownTabChange(prev, next, thread); + // A task, not a microtask: a reopen's closed-view removal lands first and cancels it. + if (from !== null) pendingPush = setTimeout(write, 0, from); + }); + + // Only Reopen Closed View removes entries, and its location check must not see our push. + const stopClosedViews = useClosedViewStore.subscribe((next, prev) => { + if (next.entries.length < prev.entries.length) cancelPush(); + }); + + const stopHistory = history.subscribe(({ location, action }) => { + pendingSkip = undefined; + const before = previous; + previous = location; + if (action.type === "BACK" || action.type === "FORWARD") { + cancelPush(); + const ref = threadRouteRef(router, location); + 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, + gone: ref !== null && threadGone(ref), + }; + const decision = decideMove(move, { thread, narrow, layout: layout() }); + if (decision.type === "show") { + restoring = true; + try { + activate(decision.tab); + } finally { + restoring = false; + } + } else if (decision.type === "skip") { + const step = action.type === "BACK" ? () => history.back() : () => history.forward(); + pendingSkip = step; + // A microtask runs before the router renders a missing thread and redirects. Memory + // history notifies inside back(), so stepping right here would re-enter this listener. + queueMicrotask(() => { + if (pendingSkip !== step) return; + pendingSkip = undefined; + step(); + }); + } + } + tagShown(); + }); + + tagShown(); + + return () => { + cancelPush(); + pendingSkip = undefined; + stopStore(); + stopClosedViews(); + stopHistory(); + }; +} + +/** + * Runs tab-history tracking for `threadRef` and calls `activate` when Back or Forward reveals a + * tab in narrow mode. In wide mode it records no entries and skips same-URL leftover entries. It + * also skips entries of deleted threads in both modes. + */ +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, + threadGone: readThreadGone, + }), + [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..bb326a9e7d459 --- /dev/null +++ b/apps/web/src/fork/workArea/tabHistoryTags.ts @@ -0,0 +1,68 @@ +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; +}; + +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); + 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); + } + try { + storage()?.setItem(STORAGE_KEY, JSON.stringify([...tags])); + } catch { + // Full or blocked storage keeps the tags for this page load only. + } + }, + }; +} + +// 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/fork/workArea/useThreadGone.ts b/apps/web/src/fork/workArea/useThreadGone.ts index c3548b45f467e..6e474c3a0ab2e 100644 --- a/apps/web/src/fork/workArea/useThreadGone.ts +++ b/apps/web/src/fork/workArea/useThreadGone.ts @@ -1,9 +1,10 @@ import { useAtomValue } from "@effect/atom-react"; import type { ScopedThreadRef } from "@t3tools/contracts"; -import { useQuietThreadShell } from "~/state/entities"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { readThreadShell, useQuietThreadShell } from "~/state/entities"; import { serverEnvironment } from "~/state/server"; -import { useEnvironmentShellHasSnapshot } from "~/state/shell"; +import { environmentShell, useEnvironmentShellHasSnapshot } from "~/state/shell"; /** * Whether a shown thread is gone: false while it may still render, null until its environment's @@ -18,3 +19,16 @@ export function useThreadGone(thread: ScopedThreadRef): boolean | null { if (shell !== null || shellOmits) return false; return loaded ? true : null; } + +/** + * Returns true when `thread`'s environment shell has loaded, does not include `thread`, and the + * server does not omit threads from its shell list. + */ +export function readThreadGone(thread: ScopedThreadRef): boolean { + if (readThreadShell(thread) !== null) return false; + const config = appAtomRegistry.get(serverEnvironment.configValueAtom(thread.environmentId)); + return ( + config?.shellThreadFamilies !== true && + appAtomRegistry.get(environmentShell.hasSnapshotAtom(thread.environmentId)) + ); +}