all repos — sz-chrome-remote-cdp @ f73941cbca4a2d765b140d474ab4e05e1008d93f

pi-browser-harness, patched to drive a Chrome on another host over CDP, with castle_cdp_search web search

src/state.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
/**
 * Session persistence for pi-browser-harness.
 *
 * Persists the daemon namespace and (when applicable) the remote browser ID
 * across session reloads and branch navigation.
 */

import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";

export type BrowserState = {
  readonly namespace: string;
  readonly remoteBrowserId?: string;
};

export const defaultState = (namespace = "default"): BrowserState => ({ namespace });

export const persistState = (pi: ExtensionAPI, state: BrowserState): void => {
  pi.appendEntry<BrowserState>("browser-harness-state", state);
};

/**
 * Find the last browser-harness-state entry in the current branch
 * and return the restored state, merged with defaults.
 *
 * If `currentNamespace` is supplied (e.g. from the --browser-namespace flag),
 * it overrides whatever is in the persisted entry.
 */
export const restoreState = (ctx: ExtensionContext, currentNamespace?: string): BrowserState => {
  const branchEntries = ctx.sessionManager.getBranch();
  const fallback = defaultState(currentNamespace);
  for (let i = branchEntries.length - 1; i >= 0; i--) {
    const entry = branchEntries[i];
    if (entry?.type === "custom" && entry.customType === "browser-harness-state") {
      const data = entry.data as Partial<BrowserState> | undefined;
      if (data) {
        return {
          ...fallback,
          ...data,
          namespace: currentNamespace ?? data.namespace ?? fallback.namespace,
        };
      }
    }
  }
  return fallback;
};