Skip to content

Commit 689953c

Browse files
feat(browser): run BrowserSessions on the Browser Run binding alone (#40)
* feat(browser): JPEG screenshots with a quality setting and a named BrowserSession page type PageScreenshotRequest takes a required PNG or JPEG format; only JPEG carries a quality. BrowserSession.run's page is exported as BrowserSessionPage, because Puppeteer's Node entry declares a separate Page class that is not assignable to the browser build's. * docs(changeset): mark the required screenshot format as breaking * feat(browser): run BrowserSessions on the Browser Run binding alone REST credentials move to an optional lifecycle option. Without them, close sends the browser's own close command and reports unconfirmed cleanup, and read-only Live View fails closed with live-view-requires-rest-credentials. close now returns the cleanup it can prove. --------- Co-authored-by: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com>
1 parent 965acf6 commit 689953c

5 files changed

Lines changed: 117 additions & 52 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
"@systemfsoftware/agent-platform-cloudflare": minor
3+
"@systemfsoftware/agent": none
4+
"@systemfsoftware/agent-storage-cloudflare": none
5+
"@systemfsoftware/agent-storage-memory": none
6+
"@systemfsoftware/agent-storage-postgres": none
7+
"@systemfsoftware/agent-storage-sql": none
8+
"@systemfsoftware/agent-storage-sqlite": none
9+
"@systemfsoftware/agent-testing": none
10+
"@systemfsoftware/agent-ai-decision": none
11+
"@systemfsoftware/agent-platform-node": none
12+
"@systemfsoftware/agent-pr-review": none
13+
---
14+
15+
Run `BrowserSessions` on the Browser Run binding alone: REST credentials move to an optional `lifecycle` option, and `close` returns `"confirmed"` or `"unconfirmed"`.
16+
17+
BEHAVIOR CHANGE (breaking): pass `lifecycle: { accountId, apiToken }` instead of top-level `accountId` and `apiToken`. Without it, `getReadOnlyLiveView` fails with `live-view-requires-rest-credentials`.

‎docs/src/content/docs/guide/browser.md‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ for navigation and input. Your application owns destination access, credentials,
1111

1212
## Choose an adapter
1313

14-
| Need | Capability | Host setup |
15-
| ------------------------------------------------ | ----------------------------------------- | ------------------------------------------------------------- |
16-
| Render content, links, or selector groups | PageCapture with Quick Actions | Cloudflare browser binding |
17-
| Capture a page from Node or a Worker | PageCapture with REST | Account ID, redacted token, Effect HttpClient |
18-
| Take an ephemeral PNG or JPEG screenshot | PageScreenshot with Quick Actions | Cloudflare browser binding |
19-
| Let an agent navigate and interact with websites | BrowserUse + Code Mode + Browser Sessions | Worker Loader, browser binding, private lifecycle credentials |
14+
| Need | Capability | Host setup |
15+
| ------------------------------------------------ | ----------------------------------------- | -------------------------------------------------------------- |
16+
| Render content, links, or selector groups | PageCapture with Quick Actions | Cloudflare browser binding |
17+
| Capture a page from Node or a Worker | PageCapture with REST | Account ID, redacted token, Effect HttpClient |
18+
| Take an ephemeral PNG or JPEG screenshot | PageScreenshot with Quick Actions | Cloudflare browser binding |
19+
| Let an agent navigate and interact with websites | BrowserUse + Code Mode + Browser Sessions | Worker Loader, browser binding, optional lifecycle credentials |
2020

2121
## Capture a page
2222

@@ -163,6 +163,12 @@ session; a reference cannot recreate an expired page. `session.run` hands its ac
163163
| `keepAliveMillis` | `600_000` | Provider idle allowance; maximum `600_000` |
164164
| `commandTimeoutMillis` | `30_000` | Command limit, also bounded by remaining session lifetime |
165165

166+
`BrowserSessions.layer({ browser, lifecycle: { accountId, apiToken } })` confirms `close` through
167+
the Browser Run REST API and can mint read-only Live Views. Omit `lifecycle` to run on the binding
168+
alone: `close` then sends the browser's own close command and returns `"unconfirmed"`, because
169+
nothing confirms that the provider ended the session before its idle expiry, and
170+
`getReadOnlyLiveView` fails with reason `live-view-requires-rest-credentials`.
171+
166172
Keep session references and Live View URLs private. Human takeover requires exclusive control;
167173
read-only viewers can still see page data. Expiry of a viewing URL limits new connections, not
168174
already connected viewers.

‎examples/browser-speed/src/worker.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,10 @@ export class BrowserLab extends DurableObject<Env> {
248248
private get sessions() {
249249
return BrowserSessions.layer({
250250
browser: this.env.BROWSER,
251-
accountId: this.env.CLOUDFLARE_ACCOUNT_ID ?? '',
252-
apiToken: Redacted.make(this.env.BROWSER_RENDERING_API_TOKEN ?? ''),
251+
lifecycle: {
252+
accountId: this.env.CLOUDFLARE_ACCOUNT_ID ?? '',
253+
apiToken: Redacted.make(this.env.BROWSER_RENDERING_API_TOKEN ?? ''),
254+
},
253255
}).pipe(Layer.provide(FetchHttpClient.layer))
254256
}
255257

‎packages/platform-cloudflare/src/BrowserSession.ts‎

Lines changed: 80 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import * as Effect from 'effect/Effect'
99
import * as Exit from 'effect/Exit'
1010
import * as Fiber from 'effect/Fiber'
1111
import * as Layer from 'effect/Layer'
12+
import * as Option from 'effect/Option'
1213
import * as Redacted from 'effect/Redacted'
1314
import * as Schema from 'effect/Schema'
1415
import * as Scope from 'effect/Scope'
@@ -91,6 +92,7 @@ export class BrowserSessionError extends Schema.TaggedError<BrowserSessionError>
9192
'provider',
9293
'timeout',
9394
'cleanup',
95+
'live-view-requires-rest-credentials',
9496
]),
9597
dispatch: Schema.Literals(['not-dispatched', 'possibly-dispatched']),
9698
cleanup: Schema.Literals(['not-requested', 'confirmed', 'unconfirmed']),
@@ -365,10 +367,20 @@ const targetId = (page: Page, commandTimeoutMillis: number) =>
365367
async () => (await cdp.send('Target.getTargetInfo')).targetInfo.targetId,
366368
))
367369

368-
export interface BrowserSessionsOptions extends BrowserRunLifecycleOptions {
370+
export interface BrowserSessionsOptions {
369371
readonly browser: Pick<BrowserRun, 'fetch'>
372+
/**
373+
* Browser Run REST credentials. With them, `close` confirms termination through the REST API
374+
* and read-only Live View is available. Without them, sessions run on the binding alone:
375+
* `close` sends the browser's own close command and reports `unconfirmed`, and
376+
* `getReadOnlyLiveView` fails with `live-view-requires-rest-credentials`.
377+
*/
378+
readonly lifecycle?: BrowserRunLifecycleOptions | undefined
370379
}
371380

381+
/** `confirmed` only when the REST API reported the exact session closed. */
382+
export type BrowserSessionCleanup = 'confirmed' | 'unconfirmed'
383+
372384
/** Native Cloudflare sessions; no framework browser workflow, checkpoint transfer, or observation policy. */
373385
export class BrowserSessions extends Context.Service<
374386
BrowserSessions,
@@ -401,34 +413,21 @@ export class BrowserSessions extends Context.Service<
401413
readonly keepAlive: (
402414
sessionId: Redacted.Redacted<string>,
403415
) => Effect.Effect<void, BrowserSessionError>
416+
/**
417+
* End the session. Without lifecycle credentials the browser's own close command is sent
418+
* and the result is `unconfirmed`: the provider may keep the session until its idle expiry.
419+
*/
404420
readonly close: (
405421
sessionId: Redacted.Redacted<string>,
406-
) => Effect.Effect<void, BrowserSessionError>
422+
) => Effect.Effect<BrowserSessionCleanup, BrowserSessionError>
407423
}
408424
>()('@effect-agent/platform-cloudflare/BrowserSessions') {
409425
static readonly layerNoDeps = Layer.effect(
410426
this,
411427
Effect.gen(function*() {
412428
const binding = yield* BrowserRunBinding
413-
const lifecycle = yield* BrowserRunSessionLifecycle
414-
const readonlyLiveView = yield* BrowserRunReadonlyLiveView
415-
416-
const close = (sessionId: Redacted.Redacted<string>) =>
417-
decode(SessionId, sessionId).pipe(
418-
Effect.flatMap((id) =>
419-
lifecycle
420-
.close(id)
421-
.pipe(
422-
mapBrowserError((error) => failure('cleanup', 'not-dispatched', 'unconfirmed', error)),
423-
)
424-
),
425-
)
426-
427-
const cleanup = (sessionId: Redacted.Redacted<string>) =>
428-
close(sessionId).pipe(
429-
Effect.as('confirmed' as const),
430-
Effect.tapCause((cause) => reportBrowserCause('session.close', cause)),
431-
)
429+
const lifecycle = yield* Effect.serviceOption(BrowserRunSessionLifecycle)
430+
const readonlyLiveView = yield* Effect.serviceOption(BrowserRunReadonlyLiveView)
432431

433432
const connect = Effect.fnUntraced(function*(sessionId: Redacted.Redacted<string>) {
434433
let attachment: BrowserRunAttachment | undefined
@@ -459,6 +458,41 @@ export class BrowserSessions extends Context.Service<
459458
return { browser, retire }
460459
})
461460

461+
// Without REST credentials, connect to the exact session and send the browser's own close.
462+
// Nothing confirms that the provider ended it, so success is reported as unconfirmed.
463+
const closeOverBinding = (sessionId: Redacted.Redacted<string>) =>
464+
Effect.scoped(
465+
Effect.gen(function*() {
466+
const { browser } = yield* connect(sessionId)
467+
468+
yield* native('session.close', () => browser.close())
469+
}),
470+
).pipe(
471+
timeout({
472+
duration: '10 seconds',
473+
orElse: () => Effect.fail(failure('timeout')),
474+
}),
475+
mapBrowserError((error) => failure('cleanup', 'possibly-dispatched', 'unconfirmed', error)),
476+
Effect.as('unconfirmed' as const),
477+
)
478+
479+
const close = (sessionId: Redacted.Redacted<string>) =>
480+
decode(SessionId, sessionId).pipe(
481+
Effect.flatMap((id): Effect.Effect<BrowserSessionCleanup, BrowserSessionError> =>
482+
Option.isSome(lifecycle)
483+
? lifecycle.value.close(id).pipe(
484+
Effect.as('confirmed' as const),
485+
mapBrowserError((error) => failure('cleanup', 'not-dispatched', 'unconfirmed', error)),
486+
)
487+
: closeOverBinding(id)
488+
),
489+
)
490+
491+
const cleanup = (sessionId: Redacted.Redacted<string>) =>
492+
close(sessionId).pipe(
493+
Effect.tapCause((cause) => reportBrowserCause('session.close', cause)),
494+
)
495+
462496
const allocate = Effect.fnUntraced(function*<E, R>(
463497
input: BrowserSessionOptions,
464498
retain: (reference: BrowserSessionReference) => Effect.Effect<void, E, R>,
@@ -840,24 +874,27 @@ export class BrowserSessions extends Context.Service<
840874
getReadOnlyLiveView: (authorize, request) =>
841875
decode(BrowserRunLiveViewRequest, request).pipe(
842876
Effect.flatMap((value) =>
843-
runEffect((commandTimeoutMillis) =>
844-
authorize.pipe(
845-
Effect.andThen(() =>
846-
readonlyLiveView.mint(reference.sessionId, reference.targetId, value).pipe(
847-
Effect.tapCause((cause) => reportBrowserCause('session.readonlyLiveView', cause)),
848-
mapBrowserError((error) =>
849-
reportedBrowserError(
850-
failure('provider', 'not-dispatched', 'not-requested', error),
851-
)
852-
),
853-
)
854-
),
855-
timeout({
856-
duration: commandTimeoutMillis,
857-
orElse: () => Effect.fail(failure('timeout')),
858-
}),
877+
Option.isNone(readonlyLiveView)
878+
// Fail closed before dispatch: only REST mints provider-enforced read-only views.
879+
? Effect.fail(failure('live-view-requires-rest-credentials'))
880+
: runEffect((commandTimeoutMillis) =>
881+
authorize.pipe(
882+
Effect.andThen(() =>
883+
readonlyLiveView.value.mint(reference.sessionId, reference.targetId, value).pipe(
884+
Effect.tapCause((cause) => reportBrowserCause('session.readonlyLiveView', cause)),
885+
mapBrowserError((error) =>
886+
reportedBrowserError(
887+
failure('provider', 'not-dispatched', 'not-requested', error),
888+
)
889+
),
890+
)
891+
),
892+
timeout({
893+
duration: commandTimeoutMillis,
894+
orElse: () => Effect.fail(failure('timeout')),
895+
}),
896+
)
859897
)
860-
)
861898
),
862899
),
863900
getHandoffState: (authorize) =>
@@ -991,10 +1028,11 @@ export class BrowserSessions extends Context.Service<
9911028
)
9921029

9931030
static layer(options: BrowserSessionsOptions) {
994-
return this.layerNoDeps.pipe(
995-
Layer.provide(BrowserRunBinding.layer(options.browser)),
996-
Layer.provide(BrowserRunSessionLifecycle.layer(options)),
997-
Layer.provide(BrowserRunReadonlyLiveView.layer(options)),
1031+
const binding = this.layerNoDeps.pipe(Layer.provide(BrowserRunBinding.layer(options.browser)))
1032+
1033+
return options.lifecycle === undefined ? binding : binding.pipe(
1034+
Layer.provide(BrowserRunSessionLifecycle.layer(options.lifecycle)),
1035+
Layer.provide(BrowserRunReadonlyLiveView.layer(options.lifecycle)),
9981036
)
9991037
}
10001038
}

‎tooling/browser-run-worker-proof/src/worker.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,10 @@ export class CheckoutRun extends DurableObject<Env> {
189189
private get services() {
190190
return BrowserSessions.layer({
191191
browser: this.env.BROWSER,
192-
accountId: this.env.CLOUDFLARE_ACCOUNT_ID,
193-
apiToken: Redacted.make(this.env.BROWSER_RENDERING_API_TOKEN),
192+
lifecycle: {
193+
accountId: this.env.CLOUDFLARE_ACCOUNT_ID,
194+
apiToken: Redacted.make(this.env.BROWSER_RENDERING_API_TOKEN),
195+
},
194196
}).pipe(Layer.provide(FetchHttpClient.layer))
195197
}
196198
private close = Effect.fnUntraced(function*(this: CheckoutRun) {

0 commit comments

Comments
 (0)