Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

15.2 KB
Raw Blame
import * as Schema from "effect/Schema";
import * as Option from "effect/Option";
import { storedField } from "./lib/persistedSchema";
/**
 * Thread-scoped right-panel surface state.
 *
 * This is intentionally a shallow workspace model: it owns an ordered set of
 * surface descriptors and the active surface, while each feature continues to
 * own its durable resource state. Browser surfaces point at preview tab ids;
 * the agents list is a singleton surface.
 */
import { scopedThreadKey } from "@akeru/client-runtime/environment";
import type { ScopedThreadRef } from "@akeru/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

import { resolveStorage } from "./lib/storage";
import { createMigratingStorage } from "./lib/storageKeyMigration";

export const RIGHT_PANEL_KINDS = ["preview", "agents"] as const;

export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];

export type RightPanelSurface =
  | { id: `browser:${string}`; kind: "preview"; resourceId: string }
  | { id: "browser:new"; kind: "preview"; resourceId: null }
  | { id: "agents"; kind: "agents" };

const RIGHT_PANEL_STORAGE_KEY = "akeru:right-panel-state:v2";

// Pre-rebrand key; migrated through the wrapping storage on first write.
const LEGACY_RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";

// v9 removed the "plan" surface kind (plans render inline in the transcript).
// v10 keys pull-request surfaces by reference instead of a singleton tab.
// v11 stops persisting the pull-request list's shared panel, so a restart opens the page fresh.
// v12 drops the retired diff and pull-request surfaces.
// v13 drops the retired terminal, file explorer, and file surfaces.
const RIGHT_PANEL_STORAGE_VERSION = 13;

/** Panels keyed to the retired pull-request list page. */
const isPullRequestsPanelKey = (threadKey: string) => threadKey.endsWith(":pull-requests-panel");

export interface ThreadRightPanelState {
  isOpen: boolean;
  activeSurfaceId: string | null;
  surfaces: RightPanelSurface[];
}

interface RightPanelStoreState {
  byThreadKey: Record<string, ThreadRightPanelState>;
  open: (ref: ScopedThreadRef, kind: RightPanelKind) => void;
  openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
  activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
  closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
  closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
  closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
  closeAllSurfaces: (ref: ScopedThreadRef) => void;
  reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
  show: (ref: ScopedThreadRef) => void;
  close: (ref: ScopedThreadRef) => void;
  toggleVisibility: (ref: ScopedThreadRef) => void;
  toggle: (ref: ScopedThreadRef, kind: RightPanelKind) => void;
  removeThread: (ref: ScopedThreadRef) => void;
}

const EMPTY_THREAD_STATE: ThreadRightPanelState = {
  isOpen: false,
  activeSurfaceId: null,
  surfaces: [],
};

const agentsSurface: RightPanelSurface = { id: "agents", kind: "agents" };

const browserSurface = (tabId: string | null): RightPanelSurface =>
  tabId
    ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
    : { id: "browser:new", kind: "preview", resourceId: null };

const upsertSurface = (
  current: ThreadRightPanelState,
  surface: RightPanelSurface,
  activate = true,
): ThreadRightPanelState => ({
  isOpen: true,
  surfaces: current.surfaces.some((entry) => entry.id === surface.id)
    ? current.surfaces
    : [...current.surfaces, surface],
  activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
});

const updateThread = (
  byThreadKey: Record<string, ThreadRightPanelState>,
  threadKey: string,
  updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
): RightPanelStoreState["byThreadKey"] => {
  const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
  const next = updater(current);

  if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
    if (!(threadKey in byThreadKey)) return byThreadKey;
    const { [threadKey]: _removed, ...rest } = byThreadKey;

    return rest;
  }

  if (next === current) return byThreadKey;

  return { ...byThreadKey, [threadKey]: next };
};

const StoredSurface = Schema.Union([
  Schema.Struct({ id: Schema.Literal("agents"), kind: Schema.Literal("agents") }),
  Schema.Struct({
    id: Schema.Literal("browser:new"),
    kind: Schema.Literal("preview"),
    resourceId: Schema.Null,
  }),
  Schema.Struct({
    id: Schema.TemplateLiteral(["browser:", Schema.String]),
    kind: Schema.Literal("preview"),
    resourceId: Schema.String,
  }),
]);

const StoredThreadPanel = Schema.Struct({
  isOpen: storedField(Schema.NullOr(Schema.Boolean), null),
  activeSurfaceId: storedField(Schema.NullOr(Schema.String), null),
  surfaces: storedField(Schema.Array(storedField(Schema.NullOr(StoredSurface), null)), []),
});

const StoredPanel = Schema.Struct({
  byThreadKey: storedField(
    Schema.Record(Schema.String, storedField(Schema.NullOr(StoredThreadPanel), null)),
    {},
  ),
});

/** Decodes any persisted panel version at its storage boundary; None when it is unreadable. */
export const decodeStoredPanel = Schema.decodeUnknownOption(StoredPanel);

export function migratePersistedRightPanelState(
  storedPanel: Option.Option<typeof StoredPanel.Type>,
) {
  const decoded = Option.getOrNull(storedPanel);

  const byThreadKey = Object.fromEntries(
    Object.entries(decoded?.byThreadKey ?? {})
      .filter(([key]) => !isPullRequestsPanelKey(key))
      .map(([key, panel]) => {
        const surfaces: RightPanelSurface[] =
          panel?.surfaces.filter((surface) => surface !== null) ?? [];

        const rawActiveSurfaceId = panel?.activeSurfaceId;

        const persistedActiveSurfaceId = surfaces.some(
          (surface) => surface.id === rawActiveSurfaceId,
        )
          ? (rawActiveSurfaceId ?? null)
          : null;

        const isOpen = surfaces.length > 0 && (panel?.isOpen ?? persistedActiveSurfaceId !== null);

        const activeSurfaceId =
          persistedActiveSurfaceId ?? (isOpen ? (surfaces[0]?.id ?? null) : null);

        return [key, { isOpen, surfaces, activeSurfaceId }];
      }),
  );

  return { byThreadKey };
}

export const useRightPanelStore = create<RightPanelStoreState>()(
  persist(
    (set) => ({
      byThreadKey: {},
      open: (ref, kind) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
            if (kind === "preview") {
              const existing = current.surfaces.find((surface) => surface.kind === "preview");

              return upsertSurface(current, existing ?? browserSurface(null));
            }

            return upsertSurface(current, agentsSurface);
          }),
        })),
      openBrowser: (ref, tabId) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
            const surface = browserSurface(tabId);

            const withoutPlaceholder = tabId
              ? current.surfaces.filter((entry) => entry.id !== "browser:new")
              : current.surfaces;

            return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
          }),
        })),
      activateSurface: (ref, surfaceId) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
            current.surfaces.some((surface) => surface.id === surfaceId)
              ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
              : current,
          ),
        })),
      closeSurface: (ref, surfaceId) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
            const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);

            if (index < 0) return current;
            const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);

            if (current.activeSurfaceId !== surfaceId) {
              return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
            }

            const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;

            return {
              ...current,
              isOpen: surfaces.length > 0 && current.isOpen,
              surfaces,
              activeSurfaceId: fallback?.id ?? null,
            };
          }),
        })),
      closeOtherSurfaces: (ref, surfaceId) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
            const surface = current.surfaces.find((entry) => entry.id === surfaceId);

            if (!surface || current.surfaces.length === 1) return current;

            return {
              ...current,
              isOpen: true,
              surfaces: [surface],
              activeSurfaceId: surface.id,
            };
          }),
        })),
      closeSurfacesToRight: (ref, surfaceId) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
            const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);

            if (index < 0 || index === current.surfaces.length - 1) return current;
            const surfaces = current.surfaces.slice(0, index + 1);

            const activeStillExists = surfaces.some(
              (surface) => surface.id === current.activeSurfaceId,
            );

            return {
              ...current,
              surfaces,
              activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
            };
          }),
        })),
      closeAllSurfaces: (ref) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
            current.surfaces.length === 0
              ? current
              : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
          ),
        })),
      reconcileBrowserSurfaces: (ref, tabIds) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
            const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
            const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");

            const existingBrowser = current.surfaces.filter(
              (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
                surface.kind === "preview" &&
                surface.id !== "browser:new" &&
                validIds.has(surface.id),
            );

            const knownIds = new Set(existingBrowser.map((surface) => surface.id));

            const added = tabIds
              .filter((tabId) => !knownIds.has(`browser:${tabId}`))
              .map((tabId) => browserSurface(tabId));

            const surfaces = [...nonBrowser, ...existingBrowser, ...added];

            const activeStillExists = surfaces.some(
              (surface) => surface.id === current.activeSurfaceId,
            );

            const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");

            return {
              ...current,
              surfaces,
              activeSurfaceId: activeStillExists
                ? current.activeSurfaceId
                : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
            };
          }),
        })),
      show: (ref) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
            current.isOpen ? current : { ...current, isOpen: true },
          ),
        })),
      close: (ref) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
            current.isOpen ? { ...current, isOpen: false } : current,
          ),
        })),
      toggleVisibility: (ref) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
            ...current,
            isOpen: !current.isOpen,
          })),
        })),
      toggle: (ref, kind) =>
        set((state) => ({
          byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
            const active = current.surfaces.find(
              (surface) => surface.id === current.activeSurfaceId,
            );

            if (current.isOpen && active?.kind === kind) {
              return { ...current, isOpen: false };
            }

            if (kind === "preview") {
              const existing = current.surfaces.find((surface) => surface.kind === "preview");

              return upsertSurface(current, existing ?? browserSurface(null));
            }

            return upsertSurface(current, agentsSurface);
          }),
        })),
      removeThread: (ref) =>
        set((state) => {
          const threadKey = scopedThreadKey(ref);

          if (!(threadKey in state.byThreadKey)) return state;
          const { [threadKey]: _removed, ...rest } = state.byThreadKey;

          return { byThreadKey: rest };
        }),
    }),
    {
      name: RIGHT_PANEL_STORAGE_KEY,
      version: RIGHT_PANEL_STORAGE_VERSION,
      storage: createJSONStorage(() =>
        createMigratingStorage(
          resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
          RIGHT_PANEL_STORAGE_KEY,
          LEGACY_RIGHT_PANEL_STORAGE_KEY,
        ),
      ),
      partialize: (state) => ({
        byThreadKey: Object.fromEntries(
          Object.entries(state.byThreadKey).filter(
            ([threadKey]) => !isPullRequestsPanelKey(threadKey),
          ),
        ),
      }),
      migrate: (persistedState) =>
        migratePersistedRightPanelState(decodeStoredPanel(persistedState)),
    },
  ),
);

export function selectThreadRightPanelState(
  byThreadKey: Record<string, ThreadRightPanelState>,
  ref: ScopedThreadRef | null | undefined,
): ThreadRightPanelState {
  if (!ref) return EMPTY_THREAD_STATE;

  return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
}

export function selectActiveRightPanel(
  byThreadKey: Record<string, ThreadRightPanelState>,
  ref: ScopedThreadRef | null | undefined,
): RightPanelKind | null {
  const state = selectThreadRightPanelState(byThreadKey, ref);

  if (!state.isOpen) return null;

  return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
}

export function selectActiveRightPanelSurface(
  byThreadKey: Record<string, ThreadRightPanelState>,
  ref: ScopedThreadRef | null | undefined,
): RightPanelSurface | null {
  const state = selectThreadRightPanelState(byThreadKey, ref);

  if (!state.isOpen) return null;

  return selectSelectedRightPanelSurface(byThreadKey, ref);
}

/** The selected surface even while the panel is hidden, so a layout control can restore it. */
export function selectSelectedRightPanelSurface(
  byThreadKey: Record<string, ThreadRightPanelState>,
  ref: ScopedThreadRef | null | undefined,
): RightPanelSurface | null {
  const state = selectThreadRightPanelState(byThreadKey, ref);

  return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
}