Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: make navigateToUrlPinned tear down the tab it read from (#3365)

[._.]/ Adam Eivyef22afabdc71
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c40724a012..b4485039e7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -162,6 +162,7 @@
- **[issue-3368] A failed agent's committed work is now picked up by its retry no matter which way the agent was launched.** When a run fails with commits on its branch, cleanup deliberately preserves that branch so the retry can continue from it — but turning a preserved branch into an actual resume takes a pointer written onto the task, and only one of the three ways PortOS launches an agent was writing it. A failed direct-CLI or TUI run therefore left a branch full of finished work that nothing would ever point at: the retry started from an empty tree and redid all of it, while the previous attempt's branch sat there untouched. The PR verification added in #3358 made this easy to hit — a run that committed, pushed, and only failed to open its pull request is now retried, and under those two launch modes the retry redid the whole task instead of just opening the PR — but any failed run with commits had the same gap. All three launch paths now share one gate, which still declines to stamp a pointer on a task that has exhausted its retry budget and is waiting on a human.
- **[issue-3358] An unreachable `gh` no longer looks like a quiet repo — and an agent can no longer report success having filed no PR.** Around thirty call sites ran `gh` and turned *any* failure into an empty result, so a firewalled or unauthenticated CLI was indistinguishable from a repo with nothing going on: the PR watcher saw no PRs, the branch reconciler classified every pushed branch as "needs a PR" (and would have had an agent open duplicates on top of the ones already open), the issue reconciler saw nothing to reconcile, and none of it logged a distinguishable error. Those reads now answer with three states instead of two — the forge said nothing, the forge said nothing *exists*, or we could not ask — and every forge-dependent scheduled job (`pr-watcher`, `branch-reconcile`, `issue-reconcile`, layered intelligence, self-diagnostics) probes `gh` first and skips the cycle with one clear line rather than executing against a forge it cannot read. Separately, a run whose task shape promised a pull request is now verified against the forge before it is recorded complete: an agent that commits, pushes over SSH (unaffected by an outbound block) and then fails to create the PR is recorded as needing attention with the branch named, not as "Completed successfully" — and "we could not confirm the PR" is kept distinct from "there is no PR", so a network outage is treated as environmental instead of denting the task type's measured success rate.
- **[issue-3359] The prompt-integrity snapshot now pins prompt bytes instead of the machine that generated it.** `taskPromptDefaults.test.js` hashes every current and preserved-historical prompt body against a checked-in snapshot, because editing a preserved body silently strands every other install on a prompt it can no longer recognize as an upgradable default. Prompt bodies embed this install's API origin, so hashing normalized it away first — but only the *runtime* origin, while the historical bodies written before that interpolation existed hardcode `http://localhost:5555`. The snapshot therefore only reproduced on a machine whose own origin happened to equal that literal: set a custom host, or merely run the suite in a shell with `PORT` set (as every CoS agent does), and five untouched bodies hashed differently and the suite failed reporting drift that had not happened. Regenerating the snapshot there would have been the damaging fix — it blesses whatever edited a preserved body, which is the one thing this test exists to catch. Hashing now collapses the frozen legacy origin too, which reproduces the committed snapshot byte for byte on every install, and the shared hasher is what both the test and a new `scripts/regen-prompt-integrity-snapshot.js` use, so the regeneration path can no longer normalize differently from the assertion. The guard is also in the CI planner's always-run list now: it covers a cross-install contract nothing else covers, so no impact scope may scope it out.
+- **[issue-3365] A pinned browser read now closes its own scratch tab, instead of every call site being expected to remember.** `navigateToUrlPinned` opens a fresh Chrome tab per call and tore it down itself on a refusal, but on success handed the caller a tab the caller was supposed to close — a convention that had already been broken twice, once leaving a tab behind for every catalog URL ingested and once for every Stacker News identity check, each fixed by hand-writing another close at the call site. The function already knows which case it is in: a caller that passes `evaluateExpression` did its DOM read on that same session and wants nothing back, while a caller that omits one wants the tab *as* the deliverable. So teardown now defaults to on exactly when an expression was supplied, the three read call sites no longer close anything, and the browser handoff and `POST /api/browser/navigate` still get their tab. `closeAfterRead: false` remains for a future caller that wants to read and keep the tab.
## Three.js Models
diff --git a/server/integrations/stackerNews/browserReader.js b/server/integrations/stackerNews/browserReader.js
index e3375f8810..a4ba3a9d00 100644
--- a/server/integrations/stackerNews/browserReader.js
+++ b/server/integrations/stackerNews/browserReader.js
@@ -15,7 +15,7 @@
// browser-sourced item is indistinguishable downstream from an API-sourced one:
// same hashing, same `inspectUntrustedContent` treatment, same columns.
import { isPrivateAddress } from '../../lib/safeUrlFetch.js';
-import { closeCdpPage, navigateToUrlPinned } from '../../services/browserService.js';
+import { navigateToUrlPinned } from '../../services/browserService.js';
import { STACKER_NEWS_IDENTITY_EXPRESSION, stackerNewsBrowserOrigin as ORIGIN, verifyFinalOrigin } from '../../services/stackerNewsBrowser.js';
const SETTLE_MS = 1_500;
@@ -112,20 +112,18 @@ const verifyFinalLocation = (requestedUrl, finalUrl) => {
}
};
-// Every read: pinned navigation, public-address check, location verification,
-// then tear the tab down. Read tabs are scratch — a five-page sync would
-// otherwise leave five tabs open in the user's browser per territory.
+// Every read: pinned navigation, public-address check, location verification.
+// Read tabs are scratch — a five-page sync would otherwise leave five tabs open
+// in the user's browser per territory — and supplying `evaluateExpression` is
+// what makes `navigateToUrlPinned` tear the tab down itself, on the throwing
+// paths too. `page.id` therefore names a closed tab; do not reuse it.
async function readPage(url, evaluateExpression) {
const page = await navigateToUrlPinned(url, {
verifyRemoteIp: (ip) => !isPrivateAddress(ip),
settleMs: SETTLE_MS,
evaluateExpression,
});
- const locationError = await Promise.resolve()
- .then(() => verifyFinalLocation(url, page.url))
- .then(() => null, (error) => error);
- await closeCdpPage(page.id);
- if (locationError) throw locationError;
+ verifyFinalLocation(url, page.url);
// Anything but the envelope our own expression returns means the extractor
// found no server-rendered payload, or `Runtime.evaluate` itself threw. Fail
// loudly: a swallowed extraction failure would look like a clean empty sync
diff --git a/server/integrations/stackerNews/browserReader.test.js b/server/integrations/stackerNews/browserReader.test.js
index 45301172c8..2d8e1e7d36 100644
--- a/server/integrations/stackerNews/browserReader.test.js
+++ b/server/integrations/stackerNews/browserReader.test.js
@@ -18,7 +18,10 @@ describe('Stacker News browser read transport', () => {
await expect(readMe()).resolves.toEqual({ me: { id: '77', name: 'example_user' } });
expect(navigateToUrlPinned.mock.calls[0][0]).toBe('https://stacker.news');
expect(navigateToUrlPinned.mock.calls[0][1].evaluateExpression).toContain('__NEXT_DATA__');
- expect(closeCdpPage).toHaveBeenCalledWith('page-1');
+ // Teardown of a read tab belongs to `navigateToUrlPinned` (#3365): passing
+ // `evaluateExpression` IS the request for it, so this transport must not
+ // close anything itself — the tab is already gone when it returns.
+ expect(closeCdpPage).not.toHaveBeenCalled();
});
// The identity extractor is shared with the handoff's "Check browser identity"
@@ -110,10 +113,13 @@ describe('Stacker News browser read transport', () => {
});
});
- it('refuses a navigation that landed off the fixed origin, and still closes the tab', async () => {
+ // The off-origin refusal used to have to close the tab BEFORE throwing. The
+ // tab is now already torn down by the time the pinned navigation returns, so
+ // the throw can be direct and this module still leaks nothing.
+ it('refuses a navigation that landed off the fixed origin, without owning the tab', async () => {
navigateToUrlPinned.mockResolvedValue(page('https://example.com/~example/recent', { items: { cursor: null, items: [] } }));
await expect(readItems('example')).rejects.toThrow('left the fixed origin');
- expect(closeCdpPage).toHaveBeenCalledWith('page-1');
+ expect(closeCdpPage).not.toHaveBeenCalled();
});
// Stacker News redirects a renamed/merged territory to a different same-origin
@@ -122,7 +128,7 @@ describe('Stacker News browser read transport', () => {
it('refuses a same-origin redirect to a different territory', async () => {
navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~other/recent', { items: { cursor: null, items: [] } }));
await expect(readItems('example')).rejects.toThrow('different page than the one requested');
- expect(closeCdpPage).toHaveBeenCalledWith('page-1');
+ expect(closeCdpPage).not.toHaveBeenCalled();
});
it('tolerates a trailing-slash or case difference in the landed URL', async () => {
diff --git a/server/services/browserService.js b/server/services/browserService.js
index 63e10ce28d..1b8197c855 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -462,12 +462,13 @@ const PIN_SETUP_COMMANDS = [
];
const PIN_SETUP_ID_BASE = 10;
-// Close a CDP tab by target id (best-effort). Used to fail closed after an
-// SSRF-pin refusal so a tab that connected to a disallowed address is torn down
-// rather than left open for the DOM reader. Also exported for read-only callers
-// (e.g. the Stacker News browser read transport) that scrape one page and must
-// not leave a tab behind per sync page — unlike a handoff, whose tab is the
-// deliverable.
+// Close a CDP tab by target id (best-effort). Used by `navigateToUrlPinned` to
+// fail closed after an SSRF-pin refusal (a tab that connected to a disallowed
+// address is torn down rather than left open for the DOM reader) AND to tear
+// down a tab it read from itself (`closeAfterRead`). Read callers should NOT
+// call this for a tab whose read `navigateToUrlPinned` performed — that tab is
+// already closed. It stays exported for callers that own a tab outright: a
+// handoff, or `POST /api/browser/navigate`, whose tab IS the deliverable.
export async function closeCdpPage(id) {
if (!id) return;
await cdpRequest(`/json/close/${id}`, { timeout: HEALTH_TIMEOUT_MS }).catch(() => {});
@@ -597,6 +598,22 @@ export function ssrfPinRefusalReason(messages, verifyRemoteIp, url, topFrameId =
* through. The evaluated value is returned as `evalResult` (or null). Without
* `evaluateExpression` the caller gets a page handle to read separately.
*
+ * TAB OWNERSHIP follows the read, and is NOT the caller's to remember:
+ * `closeAfterRead` defaults to true exactly when `evaluateExpression` was
+ * supplied, because a tab we already read from is scratch — leaving it open
+ * litters the user's browser one tab per navigation (which is precisely how the
+ * catalog URL ingest and the Stacker News identity check each leaked). So the
+ * teardown happens HERE, on both the refusal path and the success path. Only a
+ * caller that omits `evaluateExpression` — one for whom the TAB is the
+ * deliverable (a browser handoff, `POST /api/browser/navigate`) — gets a tab
+ * back to close on its own schedule. Pass `closeAfterRead: false` to read AND
+ * keep the tab; passing it explicitly decides teardown either way.
+ *
+ * Because of that, `id` / `webSocketDebuggerUrl` in the return value name a
+ * CLOSED tab whenever this function performed the read. They are still returned
+ * (for logging and for the `closeAfterRead: false` case) but must NOT be used to
+ * re-derive a handoff URL, re-evaluate on the session, or close the tab again.
+ *
* The caller does NOT sleep — the settle wait happens HERE, so the DOM has had
* `settleMs` to render (and every navigation in that window is pinned) by the
* time this resolves. Returns `{ id, url, title, webSocketDebuggerUrl, evalResult }`.
@@ -607,6 +624,7 @@ export async function navigateToUrlPinned(url, {
navigateTimeoutMs = NAVIGATE_TIMEOUT_MS,
evaluateExpression = null,
evaluateTimeoutMs = CDP_EVALUATE_TIMEOUT_MS,
+ closeAfterRead = Boolean(evaluateExpression),
} = {}) {
if (typeof verifyRemoteIp !== 'function') {
throw new Error('navigateToUrlPinned requires a verifyRemoteIp(ip) predicate');
@@ -723,6 +741,10 @@ export async function navigateToUrlPinned(url, {
throw new Error(`refusing to ingest: ${result.reason}`);
}
+ // The read (if any) already happened on this session, so the tab has served
+ // its purpose — tear it down here rather than trusting every call site to.
+ if (closeAfterRead) await closeCdpPage(target.id);
+
return {
id: target.id,
url: result.finalUrl || url,
diff --git a/server/services/browserService.test.js b/server/services/browserService.test.js
index 218a0fd248..ff17641f26 100644
--- a/server/services/browserService.test.js
+++ b/server/services/browserService.test.js
@@ -1,6 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdir, readFile, rm, utimes, writeFile } from 'fs/promises';
+import { createServer } from 'http';
import { join } from 'path';
+import { WebSocketServer } from 'ws';
import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
// Shape captured from Chrome 150 when a second top-level navigation supersedes
@@ -549,3 +551,141 @@ describe('ssrfPinRefusalReason (SSRF pin gate)', () => {
expect(ssrfPinRefusalReason(msgs, allow, 'https://ex.com/article')).toMatch(/still in flight/);
});
});
+
+// ---------------------------------------------------------------------------
+// Tab ownership (#3365). `navigateToUrlPinned` opens the tab, so it — not each
+// caller — decides when the tab dies. These drive the real function against a
+// FAKE CDP endpoint (a local HTTP + WebSocket server speaking just enough of the
+// protocol) because the behaviour under test is which `/json/close/<id>` calls
+// the function itself makes. NOTE: this is a protocol-level fake, not a live
+// Chrome; it asserts the close request is issued, not that Chrome honored it.
+// ---------------------------------------------------------------------------
+describe('navigateToUrlPinned tab ownership (closeAfterRead)', () => {
+ let fake;
+ let tempRoot;
+
+ // Minimal CDP: PUT /json/new hands out a blank tab, /json/close/<id> is
+ // recorded, and the socket answers Page.navigate with a frameId + a pinned
+ // main-frame Document response, then Runtime.evaluate with `evalValue`.
+ async function startFakeCdp({ evalValue = null, remoteIPAddress = '93.184.216.34' } = {}) {
+ const opened = [];
+ const closed = [];
+ let port = 0;
+ const server = createServer((req, res) => {
+ const path = req.url || '';
+ if (req.method === 'PUT' && path.startsWith('/json/new')) {
+ const id = `tab-${opened.length + 1}`;
+ opened.push(id);
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ id, webSocketDebuggerUrl: `ws://127.0.0.1:${port}/devtools/page/${id}` }));
+ return;
+ }
+ if (path.startsWith('/json/close/')) {
+ closed.push(decodeURIComponent(path.slice('/json/close/'.length)));
+ res.writeHead(200, { 'content-type': 'text/plain' });
+ res.end('Target is closing');
+ return;
+ }
+ res.writeHead(404);
+ res.end('');
+ });
+ const wss = new WebSocketServer({ server });
+ wss.on('connection', (ws) => {
+ ws.on('message', (raw) => {
+ const msg = JSON.parse(raw.toString());
+ if (msg.method === 'Page.navigate') {
+ const url = msg.params.url;
+ ws.send(JSON.stringify({ id: msg.id, result: { frameId: 'F1' } }));
+ ws.send(JSON.stringify({
+ method: 'Network.requestWillBeSent',
+ params: { requestId: 'R1', loaderId: 'R1', frameId: 'F1', type: 'Document', request: { url } },
+ }));
+ ws.send(JSON.stringify({
+ method: 'Network.responseReceived',
+ params: { requestId: 'R1', loaderId: 'R1', frameId: 'F1', type: 'Document', response: { url, remoteIPAddress, status: 200 } },
+ }));
+ return;
+ }
+ if (msg.method === 'Runtime.evaluate') {
+ ws.send(JSON.stringify({ id: msg.id, result: { result: { value: evalValue } } }));
+ return;
+ }
+ ws.send(JSON.stringify({ id: msg.id, result: {} }));
+ });
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+ return {
+ port,
+ opened,
+ closed,
+ stop: () => new Promise((resolve) => { wss.close(() => server.close(resolve)); }),
+ };
+ }
+
+ async function importServicePointedAtFake() {
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: tempRoot });
+ });
+ const service = await import('./browserService.js');
+ await service.saveConfig({ cdpHost: '127.0.0.1', cdpPort: fake.port });
+ return service;
+ }
+
+ beforeEach(async () => {
+ vi.resetModules();
+ tempRoot = createTempDataRoot('portos-browser-pin-');
+ });
+
+ afterEach(async () => {
+ vi.doUnmock('../lib/fileUtils.js');
+ await fake?.stop();
+ fake = null;
+ await rm(tempRoot, { recursive: true, force: true });
+ });
+
+ it('tears down the tab it read from when evaluateExpression was supplied', async () => {
+ fake = await startFakeCdp({ evalValue: 'read-body' });
+ const service = await importServicePointedAtFake();
+ const page = await service.navigateToUrlPinned('https://ex.com/a', {
+ verifyRemoteIp: () => true,
+ evaluateExpression: 'document.body.innerText',
+ });
+ expect(page.evalResult).toBe('read-body');
+ expect(fake.closed).toEqual(fake.opened);
+ });
+
+ it('leaves the tab open when no evaluateExpression is given — that tab IS the deliverable', async () => {
+ fake = await startFakeCdp();
+ const service = await importServicePointedAtFake();
+ const page = await service.navigateToUrlPinned('https://ex.com/a', { verifyRemoteIp: () => true });
+ expect(page.id).toBe(fake.opened[0]);
+ expect(fake.closed).toEqual([]);
+ });
+
+ // The escape hatch: a future caller that wants to read AND keep the tab.
+ it('honors closeAfterRead:false to read the DOM and still hand back a live tab', async () => {
+ fake = await startFakeCdp({ evalValue: 'read-body' });
+ const service = await importServicePointedAtFake();
+ const page = await service.navigateToUrlPinned('https://ex.com/a', {
+ verifyRemoteIp: () => true,
+ evaluateExpression: 'document.body.innerText',
+ closeAfterRead: false,
+ });
+ expect(page.evalResult).toBe('read-body');
+ expect(fake.closed).toEqual([]);
+ });
+
+ // The refusal path already tore the tab down; `closeAfterRead` must not turn
+ // that into a second close (it returns before the success-path teardown).
+ it('tears the tab down exactly once when the pin refuses', async () => {
+ fake = await startFakeCdp({ evalValue: 'read-body', remoteIPAddress: '127.0.0.1' });
+ const service = await importServicePointedAtFake();
+ await expect(service.navigateToUrlPinned('https://ex.com/a', {
+ verifyRemoteIp: (ip) => ip !== '127.0.0.1',
+ evaluateExpression: 'document.body.innerText',
+ })).rejects.toThrow(/refusing to ingest/);
+ expect(fake.closed).toEqual(fake.opened);
+ });
+});
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
index 7d381486d1..38ba2e9c3a 100644
--- a/server/services/catalogIngestSources.js
+++ b/server/services/catalogIngestSources.js
@@ -30,10 +30,7 @@ import * as catalogDB from './catalogDB.js';
import * as brainStorage from './brainStorage.js';
import { extractIngredientsForScrap } from './catalogExtraction.js';
import { transcribe } from './voice/stt.js';
-import {
- closeCdpPage,
- navigateToUrlPinned,
-} from './browserService.js';
+import { navigateToUrlPinned } from './browserService.js';
import { lookup } from 'dns/promises';
import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
import { isSafeIngestUrl, isBlockedIngestHost } from '../lib/catalogValidation.js';
@@ -132,17 +129,16 @@ export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {})
// own resolution. The DOM read runs on the SAME pinned CDP session (via
// evaluateExpression), re-verified after the read, so no late navigation slips
// between "stop monitoring" and "read". Fails closed (tab torn down, throws)
- // on any disallowed hop.
+ // on any disallowed hop. Supplying `evaluateExpression` also makes it tear the
+ // tab down on SUCCESS — the read already happened on that CDP session, so the
+ // tab is scratch and `page.id` names a closed tab by the time we get here.
+ // Every ingested URL would otherwise leave one open in the user's browser.
const page = await navigateToUrlPinned(url, {
verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
settleMs,
evaluateExpression: expression,
});
- // The read already happened on that CDP session, so this tab is scratch —
- // every ingested URL would otherwise leave one open in the user's browser.
- await closeCdpPage(page.id);
-
const parsed = page.evalResult ? safeJSONParse(page.evalResult, null) : null;
const text = clampText(parsed?.text || '');
if (!text.trim()) throw new Error('no readable text extracted from page');
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
index 1f49dcc688..590048da58 100644
--- a/server/services/catalogIngestSources.test.js
+++ b/server/services/catalogIngestSources.test.js
@@ -119,8 +119,10 @@ describe('fetchUrlMainText', () => {
expect.objectContaining({ verifyRemoteIp: expect.any(Function), evaluateExpression: expect.any(String) }),
);
// The read ran on that session, so the tab is scratch — every ingested URL
- // would otherwise leave one open in the user's browser.
- expect(browserService.closeCdpPage).toHaveBeenCalledWith('p1');
+ // would otherwise leave one open in the user's browser. Passing
+ // `evaluateExpression` IS the request for that teardown (#3365), so this
+ // service must not close the tab itself; `navigateToUrlPinned` already did.
+ expect(browserService.closeCdpPage).not.toHaveBeenCalled();
});
it('throws when the page extracts no readable text', async () => {
diff --git a/server/services/stackerNewsBrowser.js b/server/services/stackerNewsBrowser.js
index f4890c6885..1b82fb6b78 100644
--- a/server/services/stackerNewsBrowser.js
+++ b/server/services/stackerNewsBrowser.js
@@ -1,5 +1,5 @@
import { isPrivateAddress } from '../lib/safeUrlFetch.js';
-import { closeCdpPage, navigateToUrlPinned } from './browserService.js';
+import { navigateToUrlPinned } from './browserService.js';
const ORIGIN = 'https://stacker.news';
// The ONE signed-in-identity extractor. Both the handoff identity check and the
@@ -42,10 +42,11 @@ export async function getStackerNewsBrowserIdentity() {
evaluateExpression: STACKER_NEWS_IDENTITY_EXPRESSION,
});
// The identity tab is scratch, like the read transport's (browserReader.js):
- // it is read and torn down. Only a handoff leaves a tab for the user, so
- // without this every "Check browser identity" click — and every handoff, which
- // checks identity first — piled another stacker.news tab into their browser.
- await closeCdpPage(page.id);
+ // supplying `evaluateExpression` means `navigateToUrlPinned` already read it
+ // and tore it down. Only a handoff (below, no expression) leaves a tab for the
+ // user — otherwise every "Check browser identity" click, and every handoff,
+ // which checks identity first, would pile another stacker.news tab into their
+ // browser. `page.id` names a closed tab here; do not reuse it.
verifyFinalOrigin(page.url);
return { username: page.evalResult?.username || null, url: page.url };
}
diff --git a/server/services/stackerNewsBrowser.test.js b/server/services/stackerNewsBrowser.test.js
index d64e6908e5..7cc0cca2ec 100644
--- a/server/services/stackerNewsBrowser.test.js
+++ b/server/services/stackerNewsBrowser.test.js
@@ -26,18 +26,25 @@ describe('Stacker News CDP handoff', () => {
});
// The identity read is scratch: without teardown every check (and every
- // handoff, which checks first) leaves another stacker.news tab behind.
- it('tears the identity tab down and leaves ONLY the handoff tab open', async () => {
+ // handoff, which checks first) leaves another stacker.news tab behind. That
+ // teardown is `navigateToUrlPinned`'s job now — supplying `evaluateExpression`
+ // IS the request for it (#3365) — so what this asserts is the delegation:
+ // the identity nav opts in, the handoff nav (the tab the user keeps) does not,
+ // and this module closes nothing itself.
+ it('delegates identity-tab teardown to the pinned navigation and leaves ONLY the handoff tab open', async () => {
navigateToUrlPinned
.mockResolvedValueOnce({ id: 'identity', url: 'https://stacker.news', evalResult: { username: 'example_user' } })
.mockResolvedValueOnce({ id: 'item', url: 'https://stacker.news/items/42' });
await openStackerNewsHandoff({ kind: 'item', value: '42', expectedUsername: 'example_user' });
- expect(closeCdpPage.mock.calls).toEqual([['identity']]);
+ expect(navigateToUrlPinned.mock.calls[0][1].evaluateExpression).toBeTruthy();
+ expect(navigateToUrlPinned.mock.calls[1][1]).not.toHaveProperty('evaluateExpression');
+ expect(closeCdpPage).not.toHaveBeenCalled();
});
- it('closes the identity tab on a standalone identity check', async () => {
+ it('delegates identity-tab teardown on a standalone identity check', async () => {
navigateToUrlPinned.mockResolvedValue({ id: 'identity', url: 'https://stacker.news', evalResult: { username: 'example_user' } });
await expect(getStackerNewsBrowserIdentity()).resolves.toEqual({ username: 'example_user', url: 'https://stacker.news' });
- expect(closeCdpPage).toHaveBeenCalledWith('identity');
+ expect(navigateToUrlPinned.mock.calls[0][1].evaluateExpression).toBeTruthy();
+ expect(closeCdpPage).not.toHaveBeenCalled();
});
});