Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(phone): back closes previews, survives reloads and address changes

AdityaUmale45a1184fa15c
diff --git a/src/App.tsx b/src/App.tsx
index d77a06b228..e3e1b4c838 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -32,6 +32,8 @@ import {
} from "@/components/lazy-screens";
import { useAdvancedMode } from "@/lib/interface-mode";
import { closeRoomPanel, useRoomPanelShown } from "@/lib/room-panel";
+import { closeAppPreview, useAppPreview } from "@/lib/app-preview";
+import { closeFilePreview, useFilePreview } from "@/lib/file-preview";
import { WorkspaceBackupRecovery } from "@/components/WorkspaceBackupRecovery";
import { NotificationRail, NotificationsPanel } from "@/components/NotificationsPanel";
import { useNotificationFeed } from "@/lib/notification-preferences";
@@ -96,6 +98,7 @@ import { AppPreviewPanel } from "@/components/published-apps/AppPreviewPanel";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { refreshPublishedApps } from "@/lib/own-published-apps";
import { serverFetch } from "@/lib/relay-server";
+import { replaceUrl } from "@/lib/replace-url";
function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const { state, dispatch } = useStore();
@@ -131,7 +134,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
if (computerId) {
const target = new URL(window.location.href);
target.searchParams.set("share-computer", computerId);
- window.history.replaceState(null, "", `${target.pathname}${target.search}${target.hash}`);
+ replaceUrl(`${target.pathname}${target.search}${target.hash}`);
}
dispatch({ type: "toggleAppSettings", open: true, section: "desktopWorkspaces" });
};
@@ -141,7 +144,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
if (requestedSettings === "workspaces" || (requestedSettings === "organization" && window.ogb.organization && !remoteClient) ||
(cloud && window.ogb.cloudAccount && !remoteClient)) {
url.searchParams.delete("desktop-settings");
- window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
+ replaceUrl(`${url.pathname}${url.search}${url.hash}`);
if (requestedSettings === "organization") dispatch({ type: "toggleAppSettings", open: true, section: "organization" });
else if (requestedSettings === "cloud") dispatch(CLOUD_LINK_SETTINGS);
else if (requestedSettings === "cloud-settings") dispatch({ type: "toggleAppSettings", open: true, section: "cloudAccount" });
@@ -153,7 +156,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
useEffect(() => {
const rest = takePhonePairingRequest(window.location.href);
if (rest === null) return;
- window.history.replaceState(null, "", rest);
+ replaceUrl(rest);
dispatch(phonePairingSettingsAction());
}, [dispatch]);
useConnectLink(dispatch, Boolean(state.config?.team));
@@ -194,7 +197,10 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
// On a phone, back closes the open list or side panel, and from a chat picked in the list goes back to the list.
const phoneLayout = useMediaQuery(PHONE_LAYOUT, false);
const calendarFocus = state.activeView === "routines" && state.routinesFocus.view === "calendar";
- const backPlace = { calendar: calendarFocus, drawerOpen, panelOpen, appsPage: state.pluginsOpen, drawerSteps: drawerBackSteps };
+ const appPreview = useAppPreview();
+ const filePreview = useFilePreview();
+ const preview = state.activeView === "chat" && (appPreview !== null || filePreview !== null);
+ const backPlace = { calendar: calendarFocus, drawerOpen, panelOpen, preview, appsPage: state.pluginsOpen, drawerSteps: drawerBackSteps };
usePhoneBack(phoneLayout, phoneBackSteps(backPlace), () => {
const step = phoneBackStep(backPlace);
if (step === "calendar") return dispatch({ type: "showRoutines", view: "list", botId: state.routinesFocus.botId });
@@ -205,6 +211,8 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
dispatch({ type: "closeForkPanel" });
closeRoomPanel();
closeInbox();
+ closeAppPreview();
+ closeFilePreview();
});
// A 320 panel leaves room for the open sidebar from 1040 up; a wider one from 1280. Narrower, the sidebar folds.
const collapseSidebar = sidebarFoldsForPanel(sidePanels, { wide: sidebarAndPanelFit, narrow: sidebarAndNarrowPanelFit });
diff --git a/src/components/ConnectedWorkspacesSettings.tsx b/src/components/ConnectedWorkspacesSettings.tsx
index 6b437040fb..bebda8619c 100644
--- a/src/components/ConnectedWorkspacesSettings.tsx
+++ b/src/components/ConnectedWorkspacesSettings.tsx
@@ -7,6 +7,7 @@ import { ComputerSharingSettings } from "./ComputerSharingSettings";
import { ServerList, type OwnServerSharing } from "./ServerList";
import { useStore } from "@/state/store";
import { sharedComputersEnabled } from "@/lib/feature-flags";
+import { replaceUrl } from "@/lib/replace-url";
type SavedWorkspaces = Awaited<ReturnType<NonNullable<NonNullable<Window["ogb"]>["environments"]>["state"]>>;
@@ -52,7 +53,7 @@ export function ConnectedWorkspacesSettings({ label, description }: { label?: st
if (id) setComputerId(id);
const url = new URL(window.location.href);
url.searchParams.delete("share-computer");
- window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
+ replaceUrl(`${url.pathname}${url.search}${url.hash}`);
};
consume();
return bridge?.onOpenSettings?.(consume);
diff --git a/src/hooks/use-phone-back.dom.test.ts b/src/hooks/use-phone-back.dom.test.ts
index c820846642..cf172a65a3 100644
--- a/src/hooks/use-phone-back.dom.test.ts
+++ b/src/hooks/use-phone-back.dom.test.ts
@@ -2,6 +2,7 @@
import { act, createElement as h, useState } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { replaceUrl } from "@/lib/replace-url";
import { usePhoneBack } from "./use-phone-back";
let root: Root;
@@ -127,3 +128,47 @@ it("still steps back once onto an entry whose state the app replaced", async ()
expect(back).toHaveBeenCalledTimes(1);
expect(container.textContent).toBe("1");
});
+
+it("keeps its place when the app changes the address, so Forward after Back is still not a back press", async () => {
+ await act(async () => root.render(h(Stack)));
+ replaceUrl("/?lang=fr");
+ await pressBack();
+ expect(back).toHaveBeenCalledTimes(1);
+ await pressForward();
+ expect(back, "Forward onto the changed entry is not a step back").toHaveBeenCalledTimes(1);
+ expect(container.textContent).toBe("1");
+});
+
+it("takes away the entries a reload kept when nothing is open after it", async () => {
+ entries = [{ ombPhoneBack: 0 }, { ombPhoneBack: 1 }, { ombPhoneBack: 2 }];
+ above = 2;
+ await show(true, 0);
+ expect(window.history.go).toHaveBeenCalledWith(-2);
+ expect(above, "back from here leaves the app").toBe(0);
+ expect(back).not.toHaveBeenCalled();
+});
+
+it("keeps the entries a reload kept when the same steps are open again", async () => {
+ entries = [{ ombPhoneBack: 0 }, { ombPhoneBack: 1 }];
+ above = 1;
+ await show(true, 1);
+ expect(window.history.pushState).not.toHaveBeenCalled();
+ expect(window.history.go).not.toHaveBeenCalled();
+});
+
+it("leaves the entry its own step back lands on marked for the step opened again meanwhile", async () => {
+ const settle: Array<() => void> = [];
+ vi.mocked(window.history.go).mockImplementation((delta = 0) => {
+ settle.push(() => {
+ above = Math.max(0, above + delta);
+ window.dispatchEvent(new PopStateEvent("popstate", { state: entries[above] ?? null }));
+ });
+ });
+ await show(true, 1);
+ await show(true, 0);
+ await show(true, 1);
+ await act(async () => { for (const step of settle.splice(0)) step(); });
+ expect(entries[above], "the entry the page is on is the open step's").toEqual({ ombPhoneBack: 1 });
+ await pressBack();
+ expect(back).toHaveBeenCalledTimes(1);
+});
diff --git a/src/hooks/use-phone-back.ts b/src/hooks/use-phone-back.ts
index 375247e270..f4f1088af2 100644
--- a/src/hooks/use-phone-back.ts
+++ b/src/hooks/use-phone-back.ts
@@ -1,4 +1,4 @@
-import { useEffect, useReducer, useRef } from "react";
+import { useEffect, useReducer, useRef, useState } from "react";
import { useStableCallback } from "./use-stable-callback";
/** Each entry the hook adds keeps its place above the start in its history state, so a press can tell Back from Forward. */
@@ -22,14 +22,17 @@ function withEntry(entry: number): Record<string, unknown> {
* from is not a step: the app stays where it is and the entry is taken away again.
*/
export function usePhoneBack(enabled: boolean, steps: number, back: () => void): void {
- const added = useRef(0);
+ // A reload keeps the entries added before it, with the page on one of them; count from that one.
+ const [start] = useState(() => entryOf(window.history.state) ?? 0);
+ const added = useRef(start);
const ownPops = useRef(0);
const stepBack = useStableCallback(back);
const [, redraw] = useReducer((draws: number) => draws + 1, 0);
useEffect(() => {
const wanted = enabled ? steps : 0;
if (wanted > added.current) {
- if (added.current === 0) window.history.replaceState(withEntry(0), "", window.location.href);
+ // While the app's own step back is still on its way, the current entry is the one it leaves, not the start.
+ if (added.current === 0 && ownPops.current === 0) window.history.replaceState(withEntry(0), "", window.location.href);
for (let entry = added.current + 1; entry <= wanted; entry += 1) window.history.pushState(withEntry(entry), "", window.location.href);
} else if (wanted < added.current) {
ownPops.current += 1;
diff --git a/src/lib/phone-back.test.ts b/src/lib/phone-back.test.ts
index f4647bec3b..2bead322ae 100644
--- a/src/lib/phone-back.test.ts
+++ b/src/lib/phone-back.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { phoneBackStep, phoneBackSteps, type PhoneBackPlace } from "./phone-back";
-const CHAT: PhoneBackPlace = { calendar: false, drawerOpen: false, panelOpen: false, appsPage: false, drawerSteps: 0 };
+const CHAT: PhoneBackPlace = { calendar: false, drawerOpen: false, panelOpen: false, preview: false, appsPage: false, drawerSteps: 0 };
describe("the phone's back button", () => {
it("has nothing to step back from on the first chat, so back leaves the app", () => {
@@ -27,4 +27,11 @@ describe("the phone's back button", () => {
expect(phoneBackStep({ ...CHAT, panelOpen: true, drawerSteps: 1 })).toBe("panels");
expect(phoneBackSteps({ ...CHAT, panelOpen: true, drawerSteps: 1 })).toBe(2);
});
+
+ it("closes a file or app preview over the chat like a side panel", () => {
+ const preview = { ...CHAT, preview: true, drawerSteps: 1 };
+ expect(phoneBackSteps(preview)).toBe(2);
+ expect(phoneBackStep(preview)).toBe("panels");
+ expect(phoneBackSteps({ ...preview, panelOpen: true }), "one step closes both").toBe(2);
+ });
});
diff --git a/src/lib/phone-back.ts b/src/lib/phone-back.ts
index 540608c35f..81b8072900 100644
--- a/src/lib/phone-back.ts
+++ b/src/lib/phone-back.ts
@@ -4,6 +4,8 @@ export interface PhoneBackPlace {
calendar: boolean;
drawerOpen: boolean;
panelOpen: boolean;
+ /** A file or app preview covers the chat; it has its own store, apart from the side panels, and closes with them. */
+ preview: boolean;
/** The apps page is open; it stays open under the list unless back closes it. */
appsPage: boolean;
/** Steps the bot list keeps: the open list, and a screen reached from it. */
@@ -13,7 +15,7 @@ export interface PhoneBackPlace {
export type PhoneBackStep = "calendar" | "drawer" | "panels" | "apps-page";
export function phoneBackSteps(place: PhoneBackPlace): number {
- return (place.calendar ? 1 : 0) + (place.panelOpen ? 1 : 0) + place.drawerSteps;
+ return (place.calendar ? 1 : 0) + (place.panelOpen || place.preview ? 1 : 0) + place.drawerSteps;
}
/**
@@ -23,6 +25,6 @@ export function phoneBackSteps(place: PhoneBackPlace): number {
export function phoneBackStep(place: PhoneBackPlace): PhoneBackStep {
if (place.calendar) return "calendar";
if (place.drawerOpen) return "drawer";
- if (place.panelOpen) return "panels";
+ if (place.panelOpen || place.preview) return "panels";
return place.appsPage && place.drawerSteps > 0 ? "apps-page" : "drawer";
}
diff --git a/src/lib/replace-url.ts b/src/lib/replace-url.ts
new file mode 100644
index 0000000000..c5e8a20ce3
--- /dev/null
+++ b/src/lib/replace-url.ts
@@ -0,0 +1,4 @@
+/** Changes the page's address without a new history entry, keeping the entry's state (such as the phone back step it marks). */
+export function replaceUrl(url: string): void {
+ window.history.replaceState(window.history.state ?? null, "", url);
+}
diff --git a/src/lib/session.ts b/src/lib/session.ts
index 0621efd5f6..221533ae23 100644
--- a/src/lib/session.ts
+++ b/src/lib/session.ts
@@ -95,7 +95,7 @@ export function isOwnerOrAdmin(state: SessionState | null): boolean {
export function takePairingCodeFromLocation(): string | null {
const m = /[#&]code=([^&]+)/.exec(location.hash);
if (!m) return null;
- history.replaceState(null, "", location.pathname + location.search);
+ history.replaceState(history.state ?? null, "", location.pathname + location.search);
return decodeURIComponent(m[1]);
}
@@ -103,7 +103,7 @@ export function takePairingCodeFromLocation(): string | null {
export function takeBrowserSignInFromLocation(): string | null {
if (!/[#&]signin=/.test(location.hash)) return null;
const m = /[#&]signin=(omb_pair_[A-Za-z0-9_-]{43})(?:&|$)/.exec(location.hash);
- history.replaceState(null, "", location.pathname + location.search);
+ history.replaceState(history.state ?? null, "", location.pathname + location.search);
return m ? m[1] : null;
}
@@ -116,7 +116,7 @@ export function takeInvitedEmailFromLocation(): string | null {
if (!email) return null;
params.delete("email");
const search = params.toString();
- history.replaceState(null, "", location.pathname + (search ? `?${search}` : "") + location.hash);
+ history.replaceState(history.state ?? null, "", location.pathname + (search ? `?${search}` : "") + location.hash);
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) ? email : null;
}
diff --git a/src/lib/thread-refs.ts b/src/lib/thread-refs.ts
index 15787d40ca..673d9823a4 100644
--- a/src/lib/thread-refs.ts
+++ b/src/lib/thread-refs.ts
@@ -1,3 +1,5 @@
+import { replaceUrl } from "./replace-url";
+
export interface ThreadRefCandidate {
botId: string;
botName: string;
@@ -149,7 +151,7 @@ export function takeThreadLinkFromLocation(): string | null {
params.delete("thread");
params.delete("bot");
const search = params.toString();
- window.history.replaceState(null, "", location.pathname + (search ? `?${search}` : "") + location.hash);
+ replaceUrl(location.pathname + (search ? `?${search}` : "") + location.hash);
return THREAD_URL_PREFIX + encodeURIComponent(thread) + (bot === null ? "" : "?bot=" + encodeURIComponent(bot));
}
diff --git a/src/lib/use-connect-link.ts b/src/lib/use-connect-link.ts
index 1eab804c5c..7e244a618e 100644
--- a/src/lib/use-connect-link.ts
+++ b/src/lib/use-connect-link.ts
@@ -3,6 +3,7 @@ import { useEffect, useState } from "react";
import type { Action } from "@/state/store";
import { takeConnectRequest, type TeamAdminSection } from "./connect-link";
import { useOwnerOrAdmin } from "./use-owner-or-admin";
+import { replaceUrl } from "./replace-url";
/** Opens the page a `/?connect=` link asks for, once, and leaves the address clean. A page only a team's admin is
* shown opens when this person is known to be one, and never for anyone else. */
@@ -12,7 +13,7 @@ export function useConnectLink(dispatch: (action: Action) => void, team: boolean
useEffect(() => {
const request = takeConnectRequest(window.location.href);
if (!request) return;
- window.history.replaceState(null, "", request.rest);
+ replaceUrl(request.rest);
if ("teamAdminSection" in request) setAdminSection(request.teamAdminSection);
else dispatch("section" in request ? { type: "toggleAppSettings", open: true, section: request.section } : { type: "togglePlugins", open: true, surface: request.surface });
}, [dispatch]);