aboutsummaryrefslogtreecommitdiff
path: root/src/cdp/ownership.ts
blob: f221d6a206828a6cc9d374ad05c60c38142e78bd (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
 * Tracks which tab targetIds belong to this harness session.
 *
 * The harness attaches to the user's running Chrome, which is also full of
 * the user's own tabs. Without an ownership boundary the agent could attach
 * to (or close) personal tabs by accident. The registry is the single source
 * of truth for "did this session open that tab?".
 *
 * Mutations notify a single change listener so the orchestrator can persist
 * to disk via the existing BrowserState flow without the registry needing to
 * know about the pi storage API.
 */

export type OwnershipRegistry = {
  add(targetId: string): void;
  remove(targetId: string): void;
  has(targetId: string): boolean;
  list(): ReadonlyArray<string>;
  /** Replace the full set — used on restoreState to re-hydrate from disk. */
  replaceAll(ids: ReadonlyArray<string>): void;
  setHarnessWindow(targetId: string | undefined): void;
  harnessWindow(): string | undefined;
  onChange(cb: () => void): void;
};

export const createOwnershipRegistry = (
  initial?: { readonly ownedTargetIds?: ReadonlyArray<string>; readonly harnessWindowTargetId?: string },
): OwnershipRegistry => {
  const owned = new Set<string>(initial?.ownedTargetIds ?? []);
  let harnessWindow: string | undefined = initial?.harnessWindowTargetId;
  let listener: (() => void) | null = null;

  const notify = (): void => {
    if (listener) listener();
  };

  return {
    add(targetId) {
      if (owned.has(targetId)) return;
      owned.add(targetId);
      notify();
    },
    remove(targetId) {
      if (!owned.has(targetId) && harnessWindow !== targetId) return;
      owned.delete(targetId);
      if (harnessWindow === targetId) harnessWindow = undefined;
      notify();
    },
    has(targetId) {
      return owned.has(targetId);
    },
    list() {
      return [...owned];
    },
    replaceAll(ids) {
      owned.clear();
      for (const id of ids) owned.add(id);
      notify();
    },
    setHarnessWindow(targetId) {
      if (harnessWindow === targetId) return;
      harnessWindow = targetId;
      notify();
    },
    harnessWindow() {
      return harnessWindow;
    },
    onChange(cb) {
      listener = cb;
    },
  };
};