Repository: browserbase/stagehand
File: packages/core/lib/v3/understudy/context.ts (TypeScript)

Code before:
    // Bring the tab to the foreground in headful Chrome (best effort).
    void this.conn.send("Target.activateTarget", { targetId }).catch(() => {});
  }

  public async addInitScript<Arg>(
    script: InitScriptSource<Arg>,
    arg?: Arg,
  ): Promise<void> {
    const source = await normalizeInitScriptSource(script, arg);
    if (this.initScripts.includes(source)) return;
    this.initScripts.push(source);
    const pages = this.pages();
    await Promise.all(pages.map((page) => page.registerInitScript(source)));
  }

  public async setExtraHTTPHeaders(
    headers: Record<string, string>,
  ): Promise<void> {
    const previousHeaders = this.extraHttpHeaders
      ? { ...this.extraHttpHeaders }
      : null;
    const nextHeaders = { ...headers };
    // Capture a version token so overlapping calls don't roll back newer updates.
    const version = ++this.extraHttpHeadersVersion;
    this.extraHttpHeaders = nextHeaders;

    const sessions: CDPSessionLike[] = [];
    for (const sessionId of this._sessionInit) {
      const session = this.conn.getSession(sessionId);
      if (session) sessions.push(session);
    }

    if (!sessions.length) return;

    const applyHeaders = async (
      headersToApply: Record<string, string>,
      callVersion: number,
    ): Promise<string[]> => {
      // If a newer call superseded this one, skip applying to avoid stale updates.
      if (callVersion !== this.extraHttpHeadersVersion) return [];
      const results = await Promise.allSettled(
        sessions.map(async (session) => {
          await session.send("Network.enable");
          await session.send("Network.setExtraHTTPHeaders", {
            headers: headersToApply,
          });
        }),
      );

      return results
        .map((result, index) => ({ result, session: sessions[index] }))

Review comment (bug):
I dont think versioning is needed if we just make calls idempotent mapping updates.

Object updates are atomic in JS so idempotent updates should be possible:

```ts
send("Network.enable")

for (const [key, val] of Object.entries(nextHeaders)) {
    try {
		// incrementally update set headers, one new key:val at a time
        send("Network.setExtraHTTPHeaders", { headers: this.extraHttpHeaders })
        this.extraHttpHeaders[key] = val   // last write wins
    } catch(e) {
        // if any header setting fails, dont persist it in the cumulative state
        console.log(`Failed to set header: ...; skipping`)
    }
}
```

That way a user can do:

```ts
ctx.setExtraHTTPHeaders({'x-some-key': 'some-val'})
// then later
ctx.setExtraHTTPHeaders({'x-some-other-key': 'some-otherval'})
```

and the second will merge cleanly with the first instead of resetting the entire headers state.

If they want to clear existing headers they can always do:

```ts
ctx.setExtraHTTPHeaders({'x-some-key': null})
ctx.setExtraHTTPHeaders({'x-some-other-key': null})

// or nuke everything
const headers_reset = Object.fromEntries(Object.entries(ctx.extraHttpHeaders).map(([key, val]) => [key, null]))
ctx.etExtraHTTPHeaders(headers_reset)
```

Code after:
    // remove prior entry if any
    const i = this._pageOrder.indexOf(tid);
    if (i !== -1) this._pageOrder.splice(i, 1);
    this._pageOrder.push(tid);
  }

  /** Remove a page target from the recency list (used on close). */
  private _removeFromOrder(tid: TargetId): void {
    const i = this._pageOrder.indexOf(tid);
    if (i !== -1) this._pageOrder.splice(i, 1);
  }

  /** Return the current active Page (most-recent page that still exists). */
  public activePage(): Page | undefined {
    // prune any stale ids from the tail
    for (let i = this._pageOrder.length - 1; i >= 0; i--) {
      const tid = this._pageOrder[i]!;
      const p = this.pagesByTarget.get(tid);
      if (p) return p;
      // stale — remove and continue
      this._pageOrder.splice(i, 1);
    }
    // fallback: pick the newest by createdAt if order is empty
    let newestTid: TargetId | undefined;
    let newestTs = -1;
    for (const [tid] of this.pagesByTarget) {
      const ts = this.createdAtByTarget.get(tid) ?? 0;
      if (ts > newestTs) {
        newestTs = ts;
        newestTid = tid;
      }
    }
    return newestTid ? this.pagesByTarget.get(newestTid) : undefined;
  }

  /** Explicitly mark a known Page as the most-recent active page (and focus it). */
  public setActivePage(page: Page): void {
    let targetId = page.targetId();
    if (this.pagesByTarget.get(targetId) !== page) {
      const lookup = this.findTargetIdByPage(page);
      if (!lookup) {
        v3Logger({
          category: "ctx",
          message: "setActivePage called with unknown Page",
          level: 2,
          auxiliary: {
            targetId: { value: String(targetId), type: "string" },
          },
        });
        return;
      }