The platform for continuously improving AI agents.
import { defaultParseSearch, redirect, type SearchMiddleware } from "@tanstack/react-router";
export function workspaceSection(pathname: string) {
const section = pathname.split("/").filter(Boolean)[0];
return section === "capabilities" ? "/agent" : section ? `/${section}` : "/";
}
export function newWorkspaceTab(pathname: string) {
return `${workspaceSection(pathname)}:${crypto.randomUUID()}`;
}
export function workspaceTabId(pathname: string, search: Record<string, unknown>) {
if (pathname === "/")
return typeof search.workspace === "string" && search.workspace
? `chat:${search.workspace}`
: "home";
const section = workspaceSection(pathname);
return typeof search.workspaceTab === "string" && search.workspaceTab.startsWith(`${section}:`)
? search.workspaceTab
: section;
}
export function clearStaleWorkspaceTab(location: {
pathname: string;
search: Record<string, unknown>;
hash: string;
}) {
const tab = location.search.workspaceTab;
if (
typeof tab === "string" &&
tab &&
!tab.startsWith(`${workspaceSection(location.pathname)}:`)
) {
// An empty id, not undefined: retainWorkspaceTab would restore the stale id when the key is absent, and loop.
throw redirect({
hash: location.hash,
replace: true,
search: { ...location.search, workspaceTab: "" },
to: location.pathname,
});
}
}
/** Keeps an independent tab's id across navigations that don't name one; beforeLoad drops it on leaving the section. */
export const retainWorkspaceTab: SearchMiddleware<{ workspaceTab?: string }> = ({
search,
next,
}) => {
const result = next(search);
return "workspaceTab" in result || !search.workspaceTab
? result
: { ...result, workspaceTab: search.workspaceTab };
};
export function workspaceTabDestination(href: string) {
const url = new URL(href, "http://workspace.local");
return {
hash: url.hash.slice(1),
search: { workspaceTab: undefined, ...defaultParseSearch(url.search) },
to: url.pathname,
};
}