Restore the last-viewed chat when returning to the Chats tab

The Chats tab always landed on the new-chat screen. Remember the
last-viewed chat per workspace (localStorage) and redirect plain
/chats navigations back to it when it still exists. Explicit new-chat
navigations carry a projectId in the route search and are never
redirected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
klopez4212
2026-07-07 07:45:34 +01:00
co-authored by Claude Fable 5
parent 17e18343f1
commit d24d56f809
2 changed files with 65 additions and 0 deletions
@@ -236,6 +236,59 @@ export function ChatsScreen({
selectedChatId !== null
? (chats.find((chat) => chat.id === selectedChatId) ?? null)
: null;
// Remember the last-viewed chat per workspace so returning to the Chats
// tab lands there instead of the new-chat screen. Explicit new-chat
// navigations carry a projectId in the route search (initialProjectId is
// then non-undefined) and are never redirected.
const lastChatStorageKey = activeWorkspace?.id
? `buzz:chats:last-viewed:${activeWorkspace.id}`
: null;
React.useEffect(() => {
if (!lastChatStorageKey || !selectedChat) {
return;
}
try {
window.localStorage.setItem(lastChatStorageKey, selectedChat.id);
} catch {
// Storage unavailable — restore is best-effort.
}
}, [lastChatStorageKey, selectedChat]);
const attemptedChatRestoreRef = React.useRef(false);
React.useEffect(() => {
if (selectedChatId !== null) {
// Viewing a chat re-arms the restore for the next plain visit.
attemptedChatRestoreRef.current = false;
return;
}
if (
initialProjectId !== undefined ||
chatsQuery.isLoading ||
attemptedChatRestoreRef.current
) {
return;
}
attemptedChatRestoreRef.current = true;
let storedChatId: string | null = null;
try {
storedChatId = lastChatStorageKey
? window.localStorage.getItem(lastChatStorageKey)
: null;
} catch {
storedChatId = null;
}
if (storedChatId && chats.some((chat) => chat.id === storedChatId)) {
void goChat(storedChatId, { replace: true });
}
}, [
chats,
chatsQuery.isLoading,
goChat,
initialProjectId,
lastChatStorageKey,
selectedChatId,
]);
const metadataQuery = useChatMetadataQuery(selectedChat?.id);
const metadata = metadataQuery.data ?? null;
const managedAgentsQuery = useManagedAgentsQuery();
@@ -46,4 +46,16 @@ test("switching chats does not stack headers", async ({ page }) => {
fullPage: false,
});
expect(headerCount).toBe(1);
// Leaving the Chats tab and returning restores the last-viewed chat
// instead of defaulting to the new-chat screen.
const lastChatId = page.url().split("/chats/")[1];
expect(lastChatId).toBeTruthy();
await page.getByTestId("open-agents-view").click();
await expect(page).toHaveURL(/agents/);
await page.getByTestId("open-chats-view").click();
await expect(page).toHaveURL(new RegExp(`/chats/${lastChatId}`));
await expect(page.getByTestId("chat-title")).toContainText(
"Second chat about bananas",
);
});