@beyondwork/wb-cli 0.1.53 → 0.1.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publisher": "beyondwork",
4
4
  "displayName": "Beyond Work",
5
5
  "description": "Tool for interacting with Beyond Work workblocks from VS Code and CLI.",
6
- "version": "0.1.53",
6
+ "version": "0.1.56",
7
7
  "vsce": {
8
8
  "baseContentUrl": "https://github.com/bwllaming/code/blob/HEAD/src/vscode/beyondwork",
9
9
  "baseImagesUrl": "https://github.com/bwllaming/code/raw/HEAD/src/vscode/beyondwork"
@@ -88,17 +88,20 @@ follow the confirmation warning above before sending the API request.
88
88
  intent from its message, in `git log`, `wb-cli log` and Studio. Studio's own messages use the
89
89
  same shape.
90
90
  7. **Prove it.** `wb-cli test` and `wb-cli run` check only what you pushed, and print the commit they
91
- ran on. They, `wb-cli ui` and `wb-cli chat` name a module or task by its `id` in `manifest.yaml`,
91
+ ran on. They and `wb-cli chat` name a module or task by its `id` in `manifest.yaml`,
92
92
  never by name. Run `wb-cli test [<module-id>]` when the module has tests, then `wb-cli run
93
- <module-id>`, or `wb-cli run <task-id> --inputs '{...}'`, for what you changed. `wb-cli run
93
+ <module-id>`, or `wb-cli run <task-id> --inputs '{...}'`, for what you changed. `wb-cli test`
94
+ sends one request for each module, with a limit of 180 seconds. When a module's tests need longer,
95
+ or a request fails, use `wb-cli test --by-file`: it sends one request for each test file, and
96
+ when a request fails, it stops and prints the commands that run the rest. `wb-cli run
94
97
  <task-id>` calls an invokable task without a run. It returns no run id and no logs, and
95
98
  the active run stays unchanged. A single task takes the outputs of the module's latest run, and
96
99
  `--inputs` gives only what no task of that run produced.
97
- A run stops at a task UI. Check each task UI that you changed with `wb-cli ui <task-id>`,
98
- which shows it in a headless browser with Playwright. Look at its screenshots. To go through a
99
- run, open each waiting UI with `wb-cli ui <task-id> --in-run` and press Submit.
100
- `references/browser-validation.md` describes both. Studio's Start and its "Configure & Run
101
- module" form need a browser tool in the user's signed-in browser.
100
+ A run stops at a task UI. Check the whole run in Studio on the tenant, as a person uses it, to
101
+ the result: with `wb-cli ui playwright exec <script>` when Playwright and the browser session of wb-cli
102
+ are there, otherwise in the user's browser through a browser tool. Start the module, use each
103
+ UI, press Submit, and look at the screenshots. `references/browser-validation.md` says when the
104
+ check is needed and how to choose, and describes both ways and the sign-in.
102
105
  An agent module acts only when someone chats with it. Prove it with `wb-cli chat <module-id> "<what
103
106
  a user would write>"` (`--persona <id>` picks one of its `agent_configs`): the agent loads your pushed branch, and the command prints its reply, each
104
107
  tool it called with the arguments and result, and the conversation id. Follow up with `wb-cli chat
@@ -265,7 +268,8 @@ full schemas as JSON.
265
268
  Prefer `push`, `run`, `test` and the other checkout workflows when they fit: raw API calls do not
266
269
  update local files or `.bw/workblock.json`. `api` uses the checkout's tenant and, for operations
267
270
  that use it, stream. Override these with `--tenant`, `--stream` or `--no-stream`. Body `-` reads
268
- JSON from stdin.
271
+ JSON from stdin. To call an invokable task of a deployed workblock without a checkout, such as a
272
+ tool of an agent module, use `wb-cli api invoke_workblock_task` with `--tenant`.
269
273
 
270
274
  `wb-cli query "<sql>"` reads the rows of the data model's entities in the development data
271
275
  environment, at most 1,000 rows; `--env <name>` reads another environment. `--param name=value`
@@ -1,12 +1,13 @@
1
- # Check task UIs with `wb-cli ui`
1
+ # Check a workblock in Studio
2
2
 
3
- `wb-cli run` proves Python tasks by their outputs, but a run stops at a task UI. `wb-cli ui` shows a
4
- task UI in a headless browser on this machine. You can see the UI and use it. `wb-cli ui` needs
5
- Playwright, not the user's browser.
3
+ `wb-cli run` proves Python tasks by their outputs, but a run stops at a task UI. Check the whole run
4
+ in Studio on the tenant, the page that a person uses: each screen in order, then the result.
5
+ There, every `bw.*` call of a UI behaves as it does for a person, file uploads included. No other
6
+ page shows a task UI as Studio does.
6
7
 
7
8
  ## When
8
9
 
9
- Check the UI in these cases:
10
+ Check in Studio in these cases:
10
11
 
11
12
  - A new workblock or module that a person starts.
12
13
  - A change to a task UI: the component, its `render_ui` call, the data it shows, or the outputs it
@@ -15,37 +16,87 @@ Check the UI in these cases:
15
16
 
16
17
  "Should work" from the code or the type check is a guess. Say what you saw and what you did not.
17
18
 
18
- ## What `wb-cli ui` shows
19
-
20
- | Target | Mode | The page shows | Data |
21
- | --- | --- | --- | --- |
22
- | `<task-id>` | `preview` | The task's UI, with Submit and the UI's action buttons below it. | The JSON file of `--data <file>`. Without `--data`: the data that the task showed in the workspace's latest run. |
23
- | `<module-id>` | `detached` | The UI of a UI-only module, as a Space shows it. | The data that the module gives its UI. |
24
- | `<task-id> --in-run`, or `<module-id> --in-run` | `run` | The task UI that waits in the workspace's run, as Studio shows it, with Submit and the UI's action buttons below it. | The data of that run. |
25
-
26
- - The tenant builds the UI from the workspace's last commit, not from your files. Push first. The command
27
- refuses unpushed edits, an unfinished merge, or a workspace at a different commit.
28
- - In a preview, Submit and continue record the data and send nothing. In a UI-only module, Submit,
29
- actions and continue fail, because the module has no run.
30
- - In a run, Submit and the actions `continue` and `continue_next` send the data to the run, as
31
- Studio does. `bw.continue` does nothing, as in a Studio task panel. The UI's task calls run in
32
- the run, and the UI sees the child runs that the task had when the page opened.
33
- - `--in-run` shows the UI that the run built, not your files. After a push, start a new run first.
34
- - The UI's task calls (`invokeTask`) and its collaborative documents run on the tenant, on the
35
- workspace, as your user. File uploads fail: `wb-cli ui` cannot upload files yet.
36
- - A module that is not UI-only has no UI of its own. Name one of its tasks instead.
37
- - A task call from the UI waits at most 300 s.
38
- - For a preview, the tenant builds the task's `react_component:`. When the task's `render_ui` call
39
- names another asset, pass `--asset <name>`. wb-cli takes the runtime and the CSP of the task's UI
40
- from the latest run. Without one, the runtime is `react@19` and the CSP is the default. Then pass
41
- `--runtime react@18` or `--csp '<directives>'` when `render_ui` sets them.
42
-
43
- ## Install Playwright once
44
-
45
- `--exec` and `--screenshot` load Playwright from your environment. wb-cli looks in the current
46
- directory and its parents, then in the global packages. Install it in the directory that holds your
47
- checkouts, not in a checkout. wb-cli reports every file in a checkout that the workblock does not
48
- claim.
19
+ ## Choose the browser
20
+
21
+ After the push, run `wb-cli ui playwright screenshot ../shots/studio.png`. It needs Playwright and
22
+ a signed-in browser of wb-cli.
23
+
24
+ | Result | Check with |
25
+ | --- | --- |
26
+ | Exit 0 | `wb-cli ui playwright exec <script>`: see "Drive Studio with `wb-cli ui playwright`". |
27
+ | Exit 3 with "not signed in", and your skills include `bw-local-auth` | Write the session file with that skill, then run the command again. |
28
+ | Exit 1 with a message about Playwright or Chromium, or exit 3 with "not signed in" | A browser tool that acts in the user's own browser, such as Claude in Chrome in Claude Code or the browser extension in the Codex desktop app. `wb-cli ui url` prints the URL to open. The user is signed in there already. On a login page, stop and ask the user to sign in there. |
29
+ | The same, and you have no such browser tool, or its calls fail | `wb-cli ui playwright exec <script>`, after you install Playwright and sign the browser in (below). |
30
+
31
+ Both browsers act as the user, with all of the user's rights, not only the scopes of wb-cli's token.
32
+
33
+ ## Rules in Studio
34
+
35
+ - Open only this checkout's workspace, the URL that `wb-cli ui url` prints. Opening it can publish
36
+ the conversation to its version branch (SKILL.md, The loop).
37
+ - Use only what a person who runs the workblock uses: the run controls (`Start <module>`, `Try
38
+ changes`, `Start specific module`), the controls of each task UI, Submit, the run's result, and
39
+ the details of a toast.
40
+ - Never press Deploy. Never change sharing, permissions or settings. Never delete anything.
41
+ - Never type credentials. When a login page shows, ask the user to sign in.
42
+
43
+ ## Check a run
44
+
45
+ 1. Push. `wb-cli ui url`, `exec` and `screenshot` each refuse unpushed edits, an unfinished merge,
46
+ or a workspace at a different commit, and print the workspace URL in a `ready` line. For the
47
+ user's browser, run `wb-cli ui url` and open that URL.
48
+ 2. Start the run, unless a run that you just started with `wb-cli run` waits at a task UI: Studio
49
+ shows that UI. While an older run waits, Studio shows Stop instead of Start: run
50
+ `wb-cli cancel` first. To start the run, use one of these:
51
+ - In Studio, press `Start <module>` or `Try changes` in the toolbar, or pick the module under
52
+ `Start specific module`. If Start opens the "Configure & Run module" form instead of a task
53
+ UI, stop. The module has inputs, which is a finding against step 3 of the skill, not a form to
54
+ fill in.
55
+ - `wb-cli run <module-id>`, or `wb-cli run <task-id>` to show one task's UI. A single task
56
+ takes the outputs of the module's latest run, and `--inputs '{...}'` gives only what no task
57
+ of that run produced. The run runs on the workspace, so Studio shows its task UI when the run
58
+ waits.
59
+ 3. Use each task UI as a person would. The UI is in an iframe; Submit and the other run controls
60
+ are outside the iframe, below it.
61
+ 4. To upload a file, set the file on the UI's file input. In a script:
62
+ `await ui.locator('input[type="file"]').setInputFiles("../fixtures/invoice.pdf")`. A browser tool
63
+ in the user's browser cannot always reach a file input inside the task UI, because its page
64
+ reading does not see into the iframe. Then leave the run as it waits, and do that screen with
65
+ `wb-cli ui playwright exec <script>`. If Playwright is missing, install it. If the browser of
66
+ wb-cli is not signed in, sign it in (below). For that screen:
67
+ - The script's browser shows the same waiting task UI, so the script presses no Start.
68
+ - The script fills the whole screen. What you entered in the user's browser is not in the
69
+ script's browser.
70
+ - The script sets the file, takes a screenshot, and presses Submit.
71
+ - The browser of wb-cli is signed in as the same user as the user's browser. For another user,
72
+ Studio disables Submit while the first user has the workspace open.
73
+
74
+ The user's browser then shows the next step of the run: continue there. If the install or the
75
+ sign-in fails, report the upload as not checked.
76
+ 5. A rejected Submit shows a "Submission rejected" toast for a few seconds, with the reason that
77
+ the component gave. When the component gave no reason, the toast has a "View error details"
78
+ button, which opens the data that the component rejected.
79
+ 6. When the run ends, run `wb-cli run --wait-for latest` and compare the outputs with the request.
80
+ When the next task waits at a UI, repeat steps 3 to 5 for it.
81
+
82
+ A UI-only module has no run. In Studio, pick `Show the UI of <module>` under `Start specific
83
+ module`; Studio shows its UI in the same kind of iframe.
84
+
85
+ In the user's browser, check that `document.visibilityState` is `visible`. A task UI runs in a
86
+ sandboxed iframe in a process of its own. While the tab is hidden, the clicks and keys that you send
87
+ into it are lost without an error, and screenshots still look right. If the tab is hidden, or a
88
+ click into a task UI has no effect, ask the user to bring the browser window to the front and keep
89
+ it visible. Page reading may see nothing inside the iframe. Then take a screenshot, click by
90
+ coordinates, type, and zoom in to confirm that the text arrived.
91
+
92
+ ## Drive Studio with `wb-cli ui playwright`
93
+
94
+ ### Install Playwright once
95
+
96
+ The commands of `wb-cli ui playwright` load Playwright from your environment. wb-cli looks in the
97
+ current directory and its parents, then in the global packages. Install it in the directory that
98
+ holds your checkouts, not in a checkout. wb-cli reports every file in a checkout that the workblock
99
+ does not claim.
49
100
 
50
101
  ```bash
51
102
  cd <directory-that-holds-the-checkout>
@@ -55,121 +106,112 @@ npm i -D playwright && npx playwright install chromium
55
106
  When Chromium does not start on Linux, `npx playwright install-deps chromium` installs the system
56
107
  libraries that it needs.
57
108
 
58
- ## Drive the UI
109
+ ### Sign the browser in
110
+
111
+ `wb-cli ui playwright sign-in` opens a browser window on the tenant. The user signs in there as on
112
+ any other day. wb-cli then keeps the session in `~/.config/beyondwork/browser/<tenant host>.json`,
113
+ and later runs use it. Run the command and ask the user to sign in in the window, or ask the user to
114
+ run it.
115
+
116
+ - A machine without a display, such as a remote shell, cannot open the window. Then sign in where
117
+ a window opens and pass that file with `--storage-state <file>`, or use the user's browser.
118
+ - The session lasts as long as a sign-in to the tenant lasts. When it ends, `exec` and
119
+ `screenshot` exit with code 3 and say that the browser is not signed in: choose the browser
120
+ again (above).
121
+ - The file acts as the user. Never copy it into a checkout or a report.
59
122
 
60
- Run each command from inside the checkout. `wb-cli ui` prints one JSON object per line.
123
+ ### Run a script
61
124
 
62
125
  | Route | Command | It ends |
63
126
  | --- | --- | --- |
64
- | A screenshot | `wb-cli ui <id> --screenshot ../shots/review.png` | After the PNG is written. |
65
- | A Playwright script | `wb-cli ui <id> --exec ../drive.mjs` | After the script returns. Exit 1 when it throws. |
66
- | Playwright MCP, or your own browser tool | `wb-cli ui <id>` in the background, then open the URL of the `ready` line. | On Ctrl-C (SIGINT) or SIGTERM. Exit 1 when the tenant closes the connection. |
127
+ | A screenshot | `wb-cli ui playwright screenshot ../shots/studio.png` | After the PNG is written. |
128
+ | A Playwright script | `wb-cli ui playwright exec ../drive.mjs` | After the script returns. Exit 1 when it throws. |
67
129
 
68
- `--exec` and `--screenshot` can go together: the script runs first. The screenshot shows the whole
69
- UI, up to 8000 px high.
70
-
71
- Your own browser tool must run on this machine, because the server listens on 127.0.0.1 only. The
72
- URL acts as your user on the tenant. Do not put it in a report.
130
+ `exec --screenshot <file>` also writes a PNG after the script returns: it shows the page as the
131
+ script left it. Add `--headed` to watch the browser.
73
132
 
74
133
  A script's default export gets these values. Keep the script next to the checkout, not in it.
75
134
 
76
135
  | Name | What it is |
77
136
  | --- | --- |
78
- | `page` | The Playwright page. Submit and the UI's action buttons are on it, below the UI. |
79
- | `ui` | `page.frameLocator('iframe[name="bw-ui"]')`: locators inside the task UI. |
80
- | `frame` | The task UI's `Frame`. |
81
- | `host.state()` | What the page recorded: `{ ready, mode, log, submits }`. |
82
- | `url` | The URL of the page. |
137
+ | `page` | The Playwright page. It shows the workspace in Studio. |
138
+ | `ui` | A frame locator for the task UI on screen: locators inside it reach the UI. |
139
+ | `context` | The Playwright browser context. |
140
+ | `url` | The workspace URL. |
83
141
 
84
142
  ```js
85
143
  // ../drive.mjs
86
- export default async ({ page, ui, host }) => {
144
+ export default async ({ page, ui }) => {
145
+ await page.getByTestId("start-module").click();
87
146
  await ui.getByLabel("Owner").fill("Anna");
147
+ await ui.locator('input[type="file"]').setInputFiles("../fixtures/invoice.pdf");
88
148
  await page.screenshot({ path: "../shots/filled.png" });
89
- await page.getByRole("button", { name: "Submit" }).click();
90
- // The page records the submit after the UI answers it.
91
- await page.waitForFunction(() => window.bwHeadlessHost.state.submits.length > 0);
92
- const { submits } = await host.state();
93
- return submits.at(-1);
149
+ await page.getByTestId("task-ui-action-continue").click();
150
+ // Studio removes the task UI when the run takes the data.
151
+ await ui.locator("body").waitFor({ state: "detached" });
94
152
  };
95
153
  ```
96
154
 
97
- The script runs after the UI asked for its data. Wait for what the UI renders with locators, not
98
- with fixed delays.
99
-
100
- ## Read the output
155
+ Find the controls of Studio by their test ids: `page.getByTestId("<id>")`. A test id is the same
156
+ in every language of Studio. The name of a control follows the language of the user. The page in
157
+ the user's browser has the same test ids, in the `data-testid` attribute.
101
158
 
102
- | `event` | Fields | Meaning |
103
- | --- | --- | --- |
104
- | `ready` | `url`, `frame`, `mode`, `module_id`, `task_id`, `commit_ref`, `data_from`, `run_id`, `task_run_id` | The page is served. `data_from` is `file` or `run`. In a preview, `task_run_id` is the task run whose data the preview shows. In a run, `run_id` and `task_run_id` name the run and the task run that waits. |
105
- | `host_event` | `kind`, and the fields of the kind | The page reports `ready`, `submit` (with `data`, or `error` when the component rejected it; in a run also `sent`, which is true when the run received the data), `console` (error lines of the UI), `page_error`, and `bridge` (each platform request of the UI, with `ok` and `error`). |
106
- | `result` | `value` | What the `--exec` script returned. |
107
- | `error` | `message` | The `--exec` script threw. |
108
- | `screenshot` | `path` | The PNG that `--screenshot` wrote. |
159
+ A tenant whose Studio is not yet updated has no test ids: `page.getByTestId("start-module")` finds
160
+ nothing there. On such a tenant, find a control by its name, for example
161
+ `page.getByRole("button", { name: "Start <module>" })` and `{ name: "Submit" }`. `ui` works on both.
109
162
 
110
- Look at every screenshot. A red-on-red label or a hidden button is in the picture and nowhere else.
111
- Compare each `submit` with the outputs that the request asks for.
163
+ | Control of Studio | Test id |
164
+ | --- | --- |
165
+ | `Start <module>` or `Try changes` in the toolbar. For a UI-only module, the button shows the UI. | `start-module` |
166
+ | `Start specific module`, which opens the list of modules | `start-module-menu` |
167
+ | The entry of that list that starts a module or shows its UI, by the `id` of the module in `manifest.yaml`. The entry that opens a chat with an agent module has no test id: use `wb-cli chat`. | `start-module-option-<module-id>` |
168
+ | Stop, which the toolbar shows in place of Start while a run is active | `stop-run` |
169
+ | The "Configure & Run module" form | `start-module-form` |
170
+ | Submit | `task-ui-action-continue` |
171
+ | Submit & Next | `task-ui-action-continue_next` |
172
+ | A button that the UI sets with `bw.setActions` | `task-ui-action-continue` or `task-ui-action-continue_next` when `execute` is that word. `task-ui-action-<n>` when `execute` is a function: `<n>` is the position of the action in the list, from 0. Two actions with the same `execute` word have the same test id. |
173
+ | The "Submission rejected" toast | `task-ui-submission-rejected` |
174
+ | "View error details" in that toast, when the component gave no reason | `error-details` |
175
+ | The iframe of a task UI. In a script, use `ui`: it is the visible one. Studio keeps the UIs of the other waiting tasks as hidden iframes with the same test id. | `task-ui-frame` |
112
176
 
113
- ## Finish a waiting run
177
+ Find the controls inside a task UI through `ui`, by the labels and roles of your own component.
114
178
 
115
- `wb-cli ui` without `--in-run` never continues a run. To finish a run that waits at a task UI:
179
+ Before the script and the screenshot, wb-cli waits until Studio shows the workspace and its
180
+ loading placeholders are gone, at most 60 s. Wait for what Studio and the UI render with
181
+ locators, not with fixed delays. A Playwright click waits until Studio enables the button.
116
182
 
117
- 1. Start the run with `wb-cli run <module-id>`. It reports `waiting` when a task UI waits.
118
- 2. Open that UI in the run and press Submit, as a person would:
119
- `wb-cli ui <task-id> --in-run --exec ../submit.mjs`. The script fills the UI and clicks
120
- `page.getByRole("button", { name: "Submit" })`. The `submit` event shows `sent: true` when the run
121
- received the data.
122
- 3. Run `wb-cli run --wait-for latest`. It prints the state and the outputs of every task. Compare the
123
- outputs with the request. When the next task waits at a UI, repeat step 2 for it.
183
+ ### Read the output
124
184
 
125
- To send data that you checked in a preview without the UI, use
126
- `wb-cli api continue_ui '{"task_id": "<task-run-id>", "data": {...}}'`. The task run id is the
127
- `task_run_id` of the `ready` line, or of the task in state `wait_ui` in
128
- `wb-cli run --wait-for latest --json`. When the checkout has no workspace in `.bw/workblock.json`,
129
- add `--stream <workspace-id>`, the last part of the workspace URL that `wb-cli status` prints.
185
+ Each `wb-cli ui` command prints one JSON object per line.
130
186
 
131
- When no task UI shows the result, a person sees the outputs only as raw data behind the module's
132
- output node in Studio, and not at all in a Space (`.skills/workblock-architecture`).
187
+ | `event` | Fields | Meaning |
188
+ | --- | --- | --- |
189
+ | `ready` | `url`, `workspace_id`, `commit_ref` | The workspace is at the checkout's commit. |
190
+ | `console` | `level`, `message` | An error line in the console of Studio or of a task UI. |
191
+ | `page_error` | `message` | An uncaught error in the page. |
192
+ | `result` | `value` | What the script returned. |
193
+ | `error` | `message` | The script threw. |
194
+ | `screenshot` | `path` | The PNG that wb-cli wrote. |
195
+ | `sign_in`, `signed_in` | `message`, `host` | `sign-in` waits for the user, then keeps the session. |
133
196
 
134
- ## The full Studio flow, from Start to the result
197
+ Look at every screenshot. A red-on-red label or a hidden button is in the picture and nowhere else.
198
+ Compare the outputs of `wb-cli run --wait-for latest` with the outputs that the request asks for.
135
199
 
136
- `wb-cli ui` shows one UI at a time. It does not press Studio's Start, and it does not show Studio's
137
- "Configure & Run module" form. To check what a person sees from Start through each UI to the result,
138
- use a browser tool that acts in the user's own browser, where the user is signed in to the tenant.
139
- Examples are Claude in Chrome in Claude Code and the ChatGPT browser extension in the Codex desktop
140
- app. Without one, report that flow as not checked and give the workspace URL that `wb-cli status`
141
- prints.
200
+ ## Send data without the UI
142
201
 
143
- That browser acts as the user with all of the user's rights, not only the token's scopes:
202
+ To continue a waiting run with data that you checked, without the UI, use
203
+ `wb-cli api continue_ui '{"task_id": "<task-run-id>", "data": {...}}'`. The task run id is the `id`
204
+ of the task in state `wait_ui` in `wb-cli run --wait-for latest --json`. When the checkout has no
205
+ workspace in `.bw/workblock.json`, add `--stream <workspace-id>`, the `workspace_id` of the `ready`
206
+ line. This proves the run, not the UI.
144
207
 
145
- - Open only this checkout's workspace, the URL that `wb-cli status` prints. Opening it can publish
146
- the conversation to its version branch (SKILL.md, The loop).
147
- - Press only Start, the controls of the task UIs, Submit and the details of a toast.
148
- - Never press Deploy. Never change sharing, permissions or settings. Never delete anything.
149
- - On a login page, stop and ask the user to sign in in that browser. Never type credentials.
150
-
151
- Do these steps:
152
-
153
- 1. Push, then run `wb-cli cancel`. While a run waits at a task UI, Studio shows Stop instead of
154
- Start. Then open the workspace.
155
- 2. Check that `document.visibilityState` is `visible`. A task UI runs in a sandboxed iframe in a
156
- process of its own. While the tab is hidden, the clicks and keys that you send into it are lost
157
- without an error, and screenshots still look right. If the tab is hidden, or a click into a task
158
- UI has no effect, ask the user to bring the browser window to the front and keep it visible.
159
- 3. Press `Start <module>` or `Try changes` in the toolbar, or pick the module under `Start specific
160
- module`. If Start opens the "Configure & Run module" form instead of a task UI, stop. The module
161
- has inputs, which is a finding against step 3 of the skill, not a form to fill in.
162
- 4. Use each task UI as a person would. Page reading may see nothing inside the iframe. Then take a
163
- screenshot, click by coordinates, type, and zoom in to confirm that the text arrived. Submit and
164
- the other run controls are outside the iframe, below it.
165
- 5. A rejected Submit shows a "Submission rejected" toast for a few seconds. Its "View error details"
166
- button opens the data that the component rejected, with the reason.
167
- 6. When the run ends, run `wb-cli run --wait-for latest` and compare the outputs with the request.
208
+ When no task UI shows the result, a person sees the outputs only as raw data behind the module's
209
+ output node in Studio, and not at all in a Space (`.skills/workblock-architecture`).
168
210
 
169
211
  ## Fix and report
170
212
 
171
213
  When something is wrong, fix it in the checkout, push, and check again. After three rounds on the
172
214
  same problem, stop and report what still fails and what you tried.
173
215
 
174
- Report the UIs you checked and how, the screenshots you looked at, the submits and outputs set
175
- against the request, and what you could not check and why.
216
+ Report the UIs you checked and how, the screenshots you looked at, the outputs set against the
217
+ request, and what you could not check and why.
@@ -1,71 +0,0 @@
1
- (function(){var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function t(t){return typeof t==`string`&&e.test(t)}function n(e){return typeof e==`string`&&e.startsWith(`::bw:data:`)}function r(e){return t(e)?{task_id:e}:{task_name:e}}function i(e,t){return{...r(e.taskName),workblock_id:t.workblockId,module_id:t.moduleId,inputs:e.inputArgs,commit_ref:t.commitRef,data_environment_id:t.dataEnvironmentId}}function a(e,t){return{...r(e.taskName),run_id:t.runId,inputs:e.inputArgs,ui_task_run_id:t.uiTaskRunId}}async function o(e,t){let r={...e};return await Promise.all(Object.entries(r).map(async([e,i])=>{n(i)?r[e]=await t(i):typeof i==`string`&&i.startsWith(`$$$::bw:data:`)&&(r[e]=i.substring(3))})),r}function s(e,t,n){let r=new Set,i=!1;return{mountWidget:async(a,o)=>{if(i)throw Error(`Chat is unmounted`);if(!(a instanceof HTMLElement))throw Error(`Chat widget needs an element`);let s=crypto.randomUUID(),c=document.createElement(`iframe`),l=new MessageChannel,u=!1,d=!1,f=0,p,m=(e,t)=>{u||!d||l.port1.postMessage({requestId:++f,payload:{type:`ON_EVENT`,event:e,data:t}})},h=n(`__embedded_chat_widget__${s}`,e=>{!e||typeof e!=`object`||!(`event`in e)||!(`data`in e)||(e.event===`chat_ui_state`&&(p=e.data),(e.event===`chat_ui_state`||e.event===`chat_ui_submit_failed`)&&m(e.event,e.data))}),g=()=>{u||d||(d=!0,c.contentWindow?.postMessage({type:`INIT_CHANNEL`,initialRoute:`/`},`*`,[l.port2]))},_=async()=>{u||(u=!0,r.delete(_),h(),c.removeEventListener(`load`,g),l.port1.onmessage=null,l.port1.close(),l.port2.close(),c.remove(),await e({type:`UNMOUNT_CHAT_WIDGET`,mountId:t,widgetMountId:s}))};r.add(_),l.port1.onmessage=async n=>{if(u||!n.data||`replyTo`in n.data)return;let{requestId:r,payload:i}=n.data;if(!(!Number.isFinite(r)||!i||typeof i.type!=`string`))try{i.type===`REPORT_HEIGHT`&&Number.isFinite(i.height)&&(c.style.height=`${Math.max(32,Math.min(i.height,2e3))}px`,p&&m(`chat_ui_state`,p));let n=await e({type:`CHAT_WIDGET_REQUEST`,mountId:t,widgetMountId:s,request:i});if(u)return;if(n.type!==`CHAT_WIDGET_RESPONSE`)throw Error(`Unexpected chat widget response`);l.port1.postMessage({replyTo:r,payload:n.response}),i.type===`CONSOLE_LOG`&&i.level===`fatal`&&a.dispatchEvent(new CustomEvent(`bw:widget-error`,{detail:Error(i.message)}))}catch(e){if(u)return;l.port1.postMessage({replyTo:r,payload:{type:`ERROR`,message:e instanceof Error?e.message:`Chat widget request failed`}})}};try{let n=await e({type:`PREPARE_CHAT_WIDGET`,mountId:t,widgetMountId:s,...o});if(u||i)throw Error(`Chat widget was unmounted`);if(n.type!==`PREPARE_CHAT_WIDGET_RESPONSE`)throw Error(`Unexpected chat widget response`);n.submitted&&(p={submitted:!0,submission:n.submission}),c.title=n.title;let r=new Set([`allow-scripts`,`allow-forms`,`allow-popups`,`allow-popups-to-escape-sandbox`,`allow-downloads`]);return c.setAttribute(`sandbox`,n.sandbox.split(/\s+/).filter(e=>r.has(e)).join(` `)),c.referrerPolicy=`no-referrer`,c.style.cssText=`width:100%;height:80px;border:0;display:block;`,c.addEventListener(`load`,g,{once:!0}),c.srcdoc=n.srcDoc,a.appendChild(c),{unmount:_}}catch(e){throw await _().catch(()=>{}),e}},clear:()=>{i=!0;for(let e of r)e().catch(()=>{})}}}function c(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function l(e){let t=null,n=0,r=[],i=null,a=null,o={},s={},c,l=new Map,u=new Map,d=new Map,f=new Map,p=0,m=`/`,h=null,g=null,_=[],v=new Map;function y(e){return(e??``).replace(/\s+/g,` `).trim()}function b(e,t){return y(e).toLowerCase().includes(y(t).toLowerCase())}function x(e){let t=globalThis.CSS;return t?.escape?t.escape(e):e.replace(/["\\]/g,`\\$&`)}function S(e){let t=[];return(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&t.push(...Array.from(e.labels??[]).map(e=>y(e.textContent))),e.id&&t.push(...Array.from(document.querySelectorAll(`label[for="${x(e.id)}"]`)).map(e=>y(e.textContent))),t.filter(Boolean)}function C(e){return e.split(/\s+/).map(e=>document.getElementById(e)?.textContent).map(y).filter(Boolean).join(` `)}function w(e){let t=e.tagName.toLowerCase();if(t===`button`)return`button`;if(t===`a`&&e.hasAttribute(`href`))return`link`;if(t===`textarea`)return`textbox`;if(t===`select`)return`combobox`;if(t===`form`)return`form`;if(t===`img`)return`img`;if(/^h[1-6]$/.test(t))return`heading`;if(t===`ul`||t===`ol`)return`list`;if(t===`li`)return`listitem`;if(t===`table`)return`table`;if(t===`tr`)return`row`;if(t===`td`||t===`th`)return`cell`;if(t!==`input`)return null;let n=(e.type||`text`).toLowerCase();return n===`checkbox`?`checkbox`:n===`radio`?`radio`:[`button`,`submit`,`reset`].includes(n)?`button`:n===`range`?`slider`:`textbox`}function T(e){return e.getAttribute(`role`)?.split(/\s+/)[0]||w(e)}function E(e){let t=e.getAttribute(`aria-label`);if(t)return y(t);let n=e.getAttribute(`aria-labelledby`);if(n)return C(n);let r=S(e);return r.length>0?r.join(` `):e instanceof HTMLInputElement&&[`button`,`submit`,`reset`].includes(e.type)?y(e.value):e instanceof HTMLImageElement?y(e.alt):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?y(e.placeholder):y(e.getAttribute(`title`)||e.textContent)}function D(){return Array.from(document.body.querySelectorAll(`*`))}function O(e,t){let n=e.toLowerCase();return D().filter(e=>T(e)?.toLowerCase()===n?!t||b(E(e),t):!1)}function k(e){return D().filter(t=>S(t).some(t=>b(t,e))?!0:b(t.getAttribute(`aria-label`),e))}function A(e){return D().filter(t=>t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?b(t.placeholder,e):!1)}function j(e){return D().filter(t=>b(t.textContent,e)?!Array.from(t.children).some(t=>b(t.textContent,e)):!1)}function M(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>F(e))??e[0]}async function N(e){return e.selector?document.querySelector(e.selector):e.testid?M(Array.from(document.querySelectorAll(`[data-testid="${x(e.testid)}"]`))):e.role?M(O(e.role,e.name)):e.label?M(k(e.label)):e.placeholder?M(A(e.placeholder)):e.text?M(j(e.text)):null}function P(e){return e.selector?`selector "${e.selector}"`:e.testid?`testid "${e.testid}"`:e.role&&e.name?`role "${e.role}" with name "${e.name}"`:e.role?`role "${e.role}"`:e.label?`label "${e.label}"`:e.placeholder?`placeholder "${e.placeholder}"`:e.text?`text "${e.text}"`:`empty query`}function F(e){let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}async function I(e){let t=await N(e);if(!t)return null;let n=t.getBoundingClientRect(),r={};for(let e of t.attributes)r[e.name]=e.value;return{exists:!0,visible:F(t),text:t.textContent?.trim()||``,value:t.value,attributes:r,rect:{x:n.x,y:n.y,width:n.width,height:n.height},tagName:t.tagName.toLowerCase()}}async function L(e){let t=await N(e);return t?t instanceof HTMLElement?(t.click(),{success:!0}):{success:!1,error:`Element is not clickable: ${P(e)}`}:{success:!1,error:`Element not found: ${P(e)}`}}function R(e,t){let n=e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`)?.set;r?r.call(e,t):e.value=t}async function z(e,t,n,r){let i=await N(e);return i?i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?(i.focus(),R(i,n?t:i.value+t),i.dispatchEvent(new Event(`input`,{bubbles:!0})),i.dispatchEvent(new Event(`change`,{bubbles:!0})),r&&(i.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keypress`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keyup`,{key:`Enter`,code:`Enter`,bubbles:!0}))),{success:!0}):{success:!1,error:`Element is not an input: ${P(e)}`}:{success:!1,error:`Element not found: ${P(e)}`}}async function B(e,t){let n=e?await N(e):document.activeElement;if(!(n instanceof HTMLElement))return{success:!1,error:e?`Element not found: ${P(e)}`:`No active element`};n.focus();for(let e of[`keydown`,`keypress`,`keyup`])n.dispatchEvent(new KeyboardEvent(e,{key:t,code:t,bubbles:!0,cancelable:!0}));return{success:!0}}async function V(e,t,n){let r=e?await N(e):document.scrollingElement;return r instanceof Element?(r.scrollBy({left:t,top:n,behavior:`auto`}),r.dispatchEvent(new Event(`scroll`,{bubbles:!0})),{success:!0}):{success:!1,error:e?`Element not found: ${P(e)}`:`No scrolling element`}}async function ee(e,t,n=5e3){let r=Date.now(),i=async()=>{let n=await N(e);switch(t){case`attached`:return n!==null;case`detached`:return n===null;case`visible`:return n!==null&&F(n);case`hidden`:return n===null||!F(n)}};return new Promise(a=>{let o=async()=>{if(await i()){a({success:!0});return}if(Date.now()-r>=n){a({success:!1,error:`Timeout waiting for element ${P(e)} to be ${t}`});return}requestAnimationFrame(o)};o()})}let H=null,U=null;async function te(){return H||U||(U=new Promise((e,t)=>{let n=document.createElement(`script`);n.src=`https://unpkg.com/html-to-image@1.11.13/dist/html-to-image.js`,n.onload=()=>{H=window.htmlToImage,H?e(H):t(Error(`html-to-image not found on window`))},n.onerror=()=>t(Error(`Failed to load html-to-image`)),document.head.appendChild(n)}),U)}async function ne(e){let t=document.body.style.width,n=document.documentElement.style.width,r=document.documentElement.style.overflow;e&&(document.documentElement.style.width=`${e}px`,document.body.style.width=`${e}px`,document.documentElement.style.overflow=`hidden`,document.body.offsetHeight,await new Promise(e=>requestAnimationFrame(e)));try{let e=await(await te()).toPng(document.body,{backgroundColor:`#ffffff`,pixelRatio:1});return e.startsWith(`data:image/png;base64,`)?e.split(`,`)[1]:e}catch(e){return console.error(`Error capturing screenshot:`,e),``}finally{e&&(document.body.style.width=t,document.documentElement.style.width=n,document.documentElement.style.overflow=r)}}function W(e){if(e.id)return`#${e.id}`;let t=e.getAttribute(`data-testid`);if(t)return`[data-testid="${t}"]`;let n=[e.tagName.toLowerCase()],r=e.getAttribute(`role`);r&&n.push(`[role="${r}"]`);let i=e.getAttribute(`type`);i&&n.push(`[type="${i}"]`);let a=e.getAttribute(`name`);a&&n.push(`[name="${a}"]`);let o=Array.from(e.classList).find(e=>!e.startsWith(`_`)&&e.length<30);o&&n.push(`.${o}`);let s=n.join(``);if(document.querySelectorAll(s).length===1)return s;let c=e.parentElement;return c?`${s}:nth-of-type(${Array.from(c.children).filter(t=>t.tagName===e.tagName).indexOf(e)+1})`:s}function re(){let e=[];document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`).forEach(t=>{let n=E(t)||t.value||``;e.push({text:n,selector:W(t),disabled:t.disabled||t.getAttribute(`aria-disabled`)===`true`})});let t=[];document.querySelectorAll(`input, textarea, select`).forEach(e=>{let n=e;t.push({selector:W(e),type:n.type||e.tagName.toLowerCase(),name:n.name||E(e)||void 0,value:n.value||void 0})});let n=[];document.querySelectorAll(`form`).forEach(e=>{n.push({id:e.id||void 0,name:e.name||void 0,inputCount:e.querySelectorAll(`input, textarea, select`).length})});let r=[];return document.querySelectorAll(`a[href]`).forEach(e=>{r.push({text:E(e)||``,href:e.href})}),{title:document.title,url:window.location.href,forms:n,buttons:e,inputs:t,links:r}}function ie(e){let t=e.data;`replyTo`in t?oe(t):ae(t)}async function ae(e){if(!t)throw Error(`Communication channel not initialized, but since we received a message, this should not happen`);switch(e.payload.type){case`GET_DATA`:{let n={status:`OK`};if($.onGetData)try{let e=await $.onGetData();if($._usingSetSubmitHandler)n={status:`OK`,data:e};else{if(!e||typeof e!=`object`||!(`status`in e))throw Error(`Unexpected result shape returned by bw.onGetData callback. Expected { status: "OK" | "ERROR", data?: any, error?: string }`);n=e}}catch(e){if($._usingSetSubmitHandler)n={status:`ERROR`,error:e instanceof Error?e.message:`Unknown error`};else throw e}let r={type:`GET_DATA_RESPONSE`,data:n};t.postMessage({replyTo:e.requestId,payload:r});break}case`ON_ACTION`:{let n=e.payload.key,i=r[parseInt(n,10)];if(typeof i.execute!=`string`)try{i.execute()}catch(e){console.error(`Error in action handler:`,e)}t.postMessage({replyTo:e.requestId,payload:{type:`ACK`}});break}case`ON_EVENT`:{e.payload.event===`chat_ui_state`&&(c={data:e.payload.data});let n=o[e.payload.event];if(n)try{n(e.payload.data)}catch(e){console.error(`Error in event handler:`,e)}t.postMessage({replyTo:e.requestId,payload:{type:`ACK`}});break}case`TEST_QUERY_ELEMENT`:{let n=await I(e.payload.query);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_QUERY_ELEMENT_RESPONSE`,result:n}});break}case`TEST_CLICK_ELEMENT`:{let n=await L(e.payload.query);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_CLICK_ELEMENT_RESPONSE`,...n}});break}case`TEST_TYPE_INTO_ELEMENT`:{let n=await z(e.payload.query,e.payload.text,e.payload.clear,e.payload.pressEnter);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_TYPE_INTO_ELEMENT_RESPONSE`,...n}});break}case`TEST_PRESS_KEY`:{let n=await B(e.payload.query,e.payload.key);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_PRESS_KEY_RESPONSE`,...n}});break}case`TEST_SCROLL`:{let n=await V(e.payload.query,e.payload.deltaX??0,e.payload.deltaY??600);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_SCROLL_RESPONSE`,...n}});break}case`TEST_WAIT_FOR_ELEMENT`:{let n=await ee(e.payload.query,e.payload.state,e.payload.timeout);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_WAIT_FOR_ELEMENT_RESPONSE`,...n}});break}case`TEST_GET_SCREENSHOT`:{let n=await ne(e.payload.width);t.postMessage({replyTo:e.requestId,payload:{type:`TEST_SCREENSHOT_RESPONSE`,imageBase64:n}});break}case`TEST_GET_PAGE_STRUCTURE`:{let n=re();t.postMessage({replyTo:e.requestId,payload:{type:`TEST_PAGE_STRUCTURE_RESPONSE`,structure:n}});break}case`SET_ROUTE`:{let{url:n}=e.payload;n!==m&&(m=n,h&&h(m)),t.postMessage({replyTo:e.requestId,payload:{type:`SET_ROUTE_ACK`}});break}default:t.postMessage({type:`ERROR`,message:`Unknown request type`}),e.payload}}function oe(e){let t=v.get(e.replyTo);t&&(e.payload&&e.payload.type===`ERROR`?t.reject(Error(e.payload.message??`Unknown error`)):e.payload&&t.resolve(e.payload),v.delete(e.replyTo))}async function G(e){return new Promise((r,i)=>{let a=++n;v.set(a,{resolve:r,reject:i});let o={requestId:a,payload:e};t?t.postMessage(o):_.push(o)})}function K(){o.__yjs_event__||=e=>{let t=e,n=t.data_key;n&&l.get(n)?.forEach(e=>{e(t)})},o.__yjs_events_reset__||=e=>{let t=e;u.get(t.data_key)?.forEach(e=>{e()})}}function se(){o.__graphlake_change__||=e=>{let{subscriptionId:t,...n}=e;f.get(t)?.onDelta(n)},o.__graphlake_ended__||=e=>{let t=e,n=f.get(t.subscriptionId);f.delete(t.subscriptionId),n?.onError?.(Error(t.error??`The GraphLake subscription ended: ${t.reason}`))}}function q(){return[...new Set([...d.values()].flat())]}function J(){G({type:`SET_SHORTCUTS`,shortcuts:q()}).catch(()=>{})}function ce(e){let t=e;q().includes(t.shortcut)&&document.body.dispatchEvent(new KeyboardEvent(`keydown`,{key:t.key,code:t.code,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,repeat:t.repeat,bubbles:!0,cancelable:!0,composed:!0}))}function Y(e){return(l.get(e)?.size??0)+(u.get(e)?.size??0)}function X(e){Y(e)===1&&G({type:`YJS_SUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to subscribe to YJS events:`,e)})}function Z(e){Y(e)===0&&G({type:`YJS_UNSUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to unsubscribe from YJS events:`,e)})}function le(e){if(e.source!==window.parent)return;let n=e.ports?.[0];(e.data===`INIT_CHANNEL`||e.data&&typeof e.data==`object`&&e.data.type===`INIT_CHANNEL`)&&n&&(t=n,t.onmessage=ie,typeof e.data==`object`&&e.data.initialRoute&&e.data.initialRoute!==`/`&&(m=e.data.initialRoute,h&&h(m)),_.forEach(e=>{e.payload.type===`ROUTE_CHANGED`&&(e.payload.url=m),n.postMessage(e)}))}window.addEventListener(`message`,le);async function Q(e){r=e,await G({type:`SET_ACTIONS`,actions:e.map((e,t)=>{let n;return n=typeof e.execute==`string`?e.execute:t.toString(),{label:e.label,disabled:e.disabled,variant:e.variant,key:n}})})}let $={request:G,saveBlob:async e=>{let t=await G({type:`SAVE_BLOB`,blob:e});if(t.type===`SAVE_BLOB_RESPONSE`)return t.blobRef;throw Error(`Failed to save blob`)},fetchBlob:async e=>{if(typeof e!=`string`||!e.startsWith(`::bw:data:`))throw Error(`Unexpected argument to bw.fetchBlob. Argument is not a blob reference.`);let t=await G({type:`FETCH_BLOB`,blobRef:e});if(t.type===`FETCH_BLOB_RESPONSE`)return t.blob;throw Error(`Failed to fetch blob`)},getData:async()=>{let e=await G({type:`GET_UI_DATA`});if(e.type===`GET_UI_DATA_RESPONSE`)return e.data;throw Error(`Failed to get data`)},invokeTask:(async(e,t,n=30,r=void 0)=>{let i=await G({type:`INVOKE_TASK`,taskName:e,inputArgs:t,timeout:n});if(i.type===`INVOKE_RESPONSE`)return r?i.result[r]:{...i,status:`OK`};throw Error(`Failed to invoke task`)}),continue:async e=>{await G({type:`CONTINUE_UI`,inputArgs:e})},setActions:e=>{let t=r,n=i,a=Symbol(`actions`);return i=a,Q(e),()=>{i===a&&(i=n,Q(t))}},setEventHandler:(e,t)=>{let n=Symbol(`eventHandler`);if(o[e]=t,s[e]=n,e===`chat_ui_state`&&c)try{t(c.data)}catch{}return()=>{s[e]===n&&(delete o[e],delete s[e])}},registerShortcuts:e=>{let t=Symbol(`shortcuts`);return d.set(t,[...e]),o.__shortcut__=ce,J(),()=>{d.delete(t)&&J()}},setSubmitHandler:e=>{let t=Symbol(`submitHandler`);return $.onGetData=e,$._usingSetSubmitHandler=!0,a=t,G({type:`SET_SUBMIT_HANDLER`,present:!0}).catch(()=>{}),()=>{a===t&&(delete $.onGetData,$._usingSetSubmitHandler=!1,a=null,G({type:`SET_SUBMIT_HANDLER`,present:!1}).catch(()=>{}))}},startChild:async e=>{let t=await G({type:`START_CHILD`,options:e});if(t.type!==`START_CHILD_RESPONSE`)throw Error(`Unexpected response to startChild: ${t.type}`);return t.result},setChildRunListener:e=>{o.__child_runs__=e,G({type:`SUBSCRIBE_CHILD_RUNS`}).then(t=>{t.type===`CHILD_RUNS_UPDATE`&&e(t.childRuns)}).catch(t=>{console.error(`Failed to subscribe to child runs:`,t),e([])})},navigate:e=>{e!==m&&(m=e,G({type:`ROUTE_CHANGED`,url:e}))},getRoute:()=>m,onRouteChange:e=>{h=e},connectRouter:e=>{let t=Symbol();g=t,G({type:`ROUTE_CHANGED`,url:m}),G({type:`ROUTES_CHANGED`,routes:e.routes??[]});let n=e.subscribe(e=>{g===t&&$.navigate(e)});return h=t=>{e.navigate(t)},e.navigate(m),()=>{n(),g===t&&(g=null,h=null,G({type:`ROUTES_CHANGED`,routes:[]}))}},navigateToStream:async e=>{await G({type:`NAVIGATE_TO_STREAM`,streamId:e})},createChat:async t=>{let n=crypto.randomUUID(),r=`__embedded_chat__${n}`,i=new Set,a=[],o=new Set,s,c=$.setEventHandler(`__embedded_chat_state__${n}`,e=>{let t=e;if(!(s&&t.revision<=s.revision)){s=t;for(let e of o)try{e(t)}catch{}}}),l=e?.(G,n,$.setEventHandler),u=!1,d=$.setEventHandler(r,e=>{let t=e;if(i.size===0&&!u){a.length>=64&&a.shift(),a.push(t);return}for(let e of i)try{e(t)}catch{}}),f=!1,p;try{p=await G({type:`CREATE_CHAT`,mountId:n,options:t})}catch(e){throw d(),c(),l?.clear(),e}if(p.type!==`CREATE_CHAT_RESPONSE`)throw d(),c(),l?.clear(),Error(`Unexpected chat creation response`);return(!s||s.revision<p.state.revision)&&(s=p.state),{streamId:p.streamId,getState:()=>s,onState:e=>{if(f)return()=>{};o.add(e);try{e(s)}catch{}return()=>{o.delete(e)}},loadMore:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`LOAD_MORE_CHAT`,mountId:n})},stop:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`STOP_CHAT`,mountId:n})},reconnect:async()=>{if(f)throw Error(`Chat is unmounted`);await G({type:`RECONNECT_CHAT`,mountId:n})},mountWidget:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);if(!l)throw Error(`Chat widgets are unavailable`);return l.mountWidget(e,t)},retry:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`RETRY_CHAT_MESSAGE`,mountId:n,messageId:e})},discard:async e=>{if(f)throw Error(`Chat is unmounted`);await G({type:`DISCARD_CHAT_MESSAGE`,mountId:n,messageId:e})},onEvent:e=>{if(f)return()=>{};u=!0,i.add(e);for(let t of a.splice(0))try{e(t)}catch{}return()=>i.delete(e)},send:async(e,t)=>{if(f)throw Error(`Chat is unmounted`);let r=await G({type:`SEND_CHAT`,mountId:n,message:e,options:t});if(r.type===`SEND_CHAT_RESPONSE`&&r.error)throw Object.assign(Error(r.error),{outgoingMessageId:r.outgoingMessageId})},unmount:async()=>{f||(f=!0,d(),c(),o.clear(),l?.clear(),i.clear(),await G({type:`UNMOUNT_CHAT`,mountId:n}))}}},openPlatformChat:async e=>{let t=await G({type:`OPEN_PLATFORM_CHAT`,emptyState:e?.emptyState,placeholder:e?.placeholder,id:e?.id,agent:e?.agent,args:e?.args,reset:e?.reset});if(t?.type===`OPEN_PLATFORM_CHAT_RESPONSE`)return{streamId:t.streamId,close:e=>$.closePlatformChat(e)};throw Error(`Unexpected response from openPlatformChat`)},closePlatformChat:async e=>{await G({type:`CLOSE_PLATFORM_CHAT`,closeStream:e?.closeStream})},emitYjsEvent:async(e,t,n)=>{let r=await G({type:`YJS_EMIT_EVENT`,dataKey:e,data:t,transient:n?.transient});if(r.type===`YJS_EMIT_EVENT_RESPONSE`)return r.event;throw Error(`Failed to emit YJS event`)},getYjsEvents:async e=>{let t=await G({type:`YJS_GET_EVENTS`,dataKey:e});if(t.type===`YJS_GET_EVENTS_RESPONSE`)return t.events;throw Error(`Failed to get YJS events`)},resetYjsEvents:async e=>{await G({type:`YJS_RESET_EVENTS`,dataKey:e})},subscribeYjsEvents:(e,t)=>{let n=l.get(e)??new Set;return n.add(t),l.set(e,n),K(),X(e),()=>{let n=l.get(e);n&&(n.delete(t),n.size===0&&l.delete(e),Z(e))}},onYjsEventsReset:(e,t)=>{let n=u.get(e)??new Set;return n.add(t),u.set(e,n),K(),X(e),()=>{let n=u.get(e);n&&(n.delete(t),n.size===0&&u.delete(e),Z(e))}},graphlake:{query:async(e,t)=>{let n=await G({type:`GRAPHLAKE_QUERY`,glq:e,params:t?.params,pageSize:t?.pageSize,pageToken:t?.pageToken});if(n.type===`GRAPHLAKE_QUERY_RESPONSE`)return n.page;throw Error(`Failed to query GraphLake`)},subscribe:(e,t,n)=>{p+=1;let r=`graphlake-${p}`;return f.set(r,{onDelta:n,onError:t?.onError}),se(),G({type:`GRAPHLAKE_SUBSCRIBE`,subscriptionId:r,glq:e,params:t?.params}).catch(e=>{let t=f.get(r);f.delete(r);let n=e instanceof Error?e:Error(String(e));t?.onError?t.onError(n):t&&console.error(`Failed to subscribe to GraphLake:`,n)}),()=>{f.delete(r)&&G({type:`GRAPHLAKE_UNSUBSCRIBE`,subscriptionId:r}).catch(()=>{})}}},bindYjsDoc:(e,t,n)=>{let r=n?.doc??new t.Doc,i=n?.awareness?.module??null,a=n?.awareness?.instance??(i?new i.Awareness(r):null),o=!1,s=!1,c=32*1024,l=e=>{let t=``;for(let n=0;n<e.length;n+=c)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+c)));return btoa(t)},u=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},d=!1,f=[],p=e=>{s=!0,t.applyUpdate(r,e),s=!1},m=t=>{o||s||$.emitYjsEvent(e,l(t)).catch(e=>{console.error(`Failed to emit yjs doc update:`,e)})};r.on(`update`,m);let h=$.subscribeYjsEvents(e,e=>{if(o)return;let t=u(e.data);if(!d){f.push(t);return}p(t)});$.getYjsEvents(e).then(e=>{if(!o){for(let t of e)p(u(t.data));for(let e of f)p(e);f.length=0,d=!0}}).catch(e=>{console.error(`Failed to load yjs snapshot:`,e),d=!0;for(let e of f)p(e);f.length=0});let g=$.onYjsEventsReset(e,()=>{if(o)return;s=!0;let e=new t.Doc,n=t.encodeStateAsUpdate(e);t.applyUpdate(r,n),s=!1}),_=`${e}:awareness`,v=null;if(a&&i){v=({added:e,updated:t,removed:n})=>{if(o)return;let r=[...e,...t,...n],s=i.encodeAwarenessUpdate(a,r);$.emitYjsEvent(_,l(s),{transient:!0}).catch(e=>{console.error(`Failed to emit awareness update:`,e)})},a.on(`update`,v);let e={unsubscribeAwareness:$.subscribeYjsEvents(_,e=>{o||i.applyAwarenessUpdate(a,u(e.data),`remote`)})};return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g(),e.unsubscribeAwareness(),v&&a.off(`update`,v),i.removeAwarenessStates(a,[r.clientID],null)}}}return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g()}}}};return $}var u=/^[a-zA-Z][a-zA-Z0-9-]*$/,d=/^[a-zA-Z0-9 \-_.+/=:*'@~%]*$/;function f(e){let t=new Map;for(let n of e.split(`;`)){let e=n.trim();if(!e)continue;let r=e.search(/\s/),i=(r===-1?e:e.slice(0,r)).toLowerCase(),a=r===-1?``:e.slice(r+1).trim().replace(/\s+/g,` `);if(!u.test(i))throw Error(`Invalid CSP directive name: ${JSON.stringify(i)}`);if(!d.test(a))throw Error(`Invalid CSP directive value for ${JSON.stringify(i)}`);t.set(i,a)}return t}function p(e,t){let n=f(e.join(`; `));if(t)for(let[e,r]of f(t))n.set(e,r);return Array.from(n,([e,t])=>t?`${e} ${t}`:e).join(`; `)}function m(e){let t=`default`,n=0,r=!1,i=new Map,a=e=>e===`granted`||e==="default"?e:`denied`,o=e=>{let t=e?.id;return typeof t==`string`?t:``},s=()=>{r||!e.bw||(r=!0,e.bw.setEventHandler(`__notification_click__`,e=>i.get(o(e))?.fire(`click`)),e.bw.setEventHandler(`__notification_close__`,e=>{let t=i.get(o(e));i.delete(o(e)),t?.fire(`close`)}))},c=async n=>{if(!e.bw)return t;s();try{let r=await e.bw.request({type:`NOTIFICATIONS_REQUEST_PERMISSION`,prompt:n});r.type===`NOTIFICATIONS_PERMISSION_RESPONSE`&&(t=a(r.permission))}catch{return t}return t};class l extends EventTarget{static get permission(){return t}static requestPermission(e){let t=c(!0);return e&&t.then(e),t}constructor(t,r){super(),n+=1,Object.assign(this,{title:String(t),body:typeof r?.body==`string`?r.body:``,tag:typeof r?.tag==`string`?r.tag:``,onclick:null,onclose:null,onerror:null,onshow:null,id:`notification-${n}`}),i.set(this.id,this);let a=()=>{i.delete(this.id),this.fire(`error`)};if(!e.bw){queueMicrotask(a);return}s(),e.bw.request({type:`NOTIFICATIONS_SHOW`,id:this.id,title:this.title,body:this.body||void 0,tag:this.tag||void 0}).then(e=>e.type===`NOTIFICATIONS_SHOW_RESPONSE`&&e.shown?this.fire(`show`):a()).catch(a)}close(){i.delete(this.id)&&(e.bw?.request({type:`NOTIFICATIONS_CLOSE`,id:this.id}).catch(()=>{}),this.fire(`close`))}fire(e){let t=new Event(e);({click:this.onclick,close:this.onclose,error:this.onerror,show:this.onshow})[e]?.call(this,t),this.dispatchEvent(t)}}e.Notification=l,c(!1)}function h(e){let t=new TextEncoder().encode(e),n=``,r=8192;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,Math.min(e+r,t.length)));return btoa(n)}function g(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return new TextDecoder().decode(r)}function _({content:e,runtime:t,csp:n,restrictEgress:r,inline:i,locale:a,reportBackground:o,blobUrl:u}){let d=[`default-src 'none'`,`connect-src blob: https://unpkg.com`,`worker-src blob:`,`frame-src about:`,`form-action 'self'`,`img-src 'self' data: blob:`,`media-src blob:`,`script-src 'self' data: 'unsafe-inline' 'wasm-unsafe-eval' blob: https://unpkg.com ${`${window.location.origin}/pdf-viewer.js`}`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net/npm/bulma@1.0.2/css/bulma.min.css`,`base-uri 'none'`],f=r?[`default-src 'none'`,`connect-src blob:`,`script-src 'unsafe-inline' 'wasm-unsafe-eval' blob: data:`,`style-src 'unsafe-inline'`,`img-src data: blob:`,`media-src blob:`,`worker-src blob:`,`frame-src about:`,`form-action 'none'`,`base-uri 'none'`].join(`; `):p(d,n);function _(){let e={log:console.log,error:console.error,warn:console.warn,info:console.info,debug:console.debug};[`log`,`error`,`warn`,`info`,`debug`].forEach(t=>{console[t]=(...n)=>{e[t](...n),window.bw&&window.bw.request({type:`CONSOLE_LOG`,level:t,message:n.map(e=>{try{return typeof e==`string`?e:JSON.stringify(e)}catch{return String(e)}}).join(` `),timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send console log via sandbox API:`,t)})}}),window.addEventListener(`error`,t=>{(async()=>{let n=window;if(!n.bw)return;let r=t.error?`${t.error.message}${t.error.stack?`
2
-
3
- Stack trace:
4
- `+t.error.stack:``}`:t.message;try{t.error&&t.error.stack&&(r=await c(t.error?t.error.message:t.message,t.error.stack))}catch(t){e.log(`Failed to map and enhance stack trace: ${t}`)}e.error(`Javascript Error: `,t),n.bw.request({type:`CONSOLE_LOG`,level:`fatal`,message:`JavaScript Error: ${s(r,5e4)}`,timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send JavaScript error via sandbox API:`,t)})})()}),window.addEventListener(`unhandledrejection`,t=>{(async()=>{e.error(`Uncaught rejection error:`,t);let n=window;if(!n.bw)return;let r=t.reason,i=`Unhandled Promise Rejection`,a;if(r instanceof Error)i=r.message+(r.stack?`
5
-
6
- Stack trace:
7
- `+r.stack:``),a=r.stack;else if(typeof r==`string`)i=r;else try{i=JSON.stringify(r)}catch{i=String(r)}try{a&&(i=await c(r.message,a))}catch{}n.bw.request({type:`CONSOLE_LOG`,level:`fatal`,message:`Unhandled Promise Rejection: ${s(i,5e4)}`,timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send promise rejection via sandbox API:`,t)})})()});let t=null;function n(){return t||(t=new Promise(e=>{if(window.StackTrace&&window.StackTraceGPS&&e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}))return;let t=e=>new Promise(t=>{let n=document.createElement(`script`);n.src=e,n.async=!0,n.onload=()=>t(!0),n.onerror=()=>t(!1),document.head.appendChild(n)});Promise.all([t(`https://unpkg.com/stacktrace-js@2.0.2/dist/stacktrace.min.js`),t(`https://unpkg.com/stacktrace-gps@3.1.2/dist/stacktrace-gps.min.js`)]).then(()=>{window.StackTrace&&window.StackTraceGPS?e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}):e(null)}),setTimeout(()=>{(!window.StackTrace||!window.StackTraceGPS)&&e(null)},5e3)}),t)}function r(e){if(!e)return null;let t=e.match(/[#@]\s*sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)/);if(!t)return null;try{return JSON.parse(atob(t[1]))}catch{return null}}let i=null;function a(){return i||(i=(async()=>{try{let e=r(window.__sandboxAppCode);if(e)return e;let t=window.__sandboxSourceMapRef;if(!t||!window.bw)return null;let n=await window.bw.fetchBlob(t);return n?JSON.parse(new TextDecoder().decode(n)):null}catch{return null}})(),i)}function o(e,t){if(!e)return null;if(!t)return new e({});let n=null;async function r(){if(n||!t)return n;let e=await new Promise(e=>{let t=document.createElement(`script`);t.src=`https://unpkg.com/source-map-js@1.2.1/source-map.js`,t.async=!0,t.onload=()=>e(window.sourceMap),t.onerror=()=>e(null),document.head.appendChild(t)});if(e&&e.SourceMapConsumer)try{n=new e.SourceMapConsumer(t)}catch{n=null}return n}let i=`/inline-app.js.map`,a=new e({sourceCache:window.__sandboxSourceMapRef?{[i]:t}:{},async ajax(e){if(e===`inline://app.js`){let e=window.__sandboxAppCode||``;return window.__sandboxSourceMapRef?`${e}\n//# sourceMappingURL=${i}`:e}return``}});return a._getMapping=async e=>{let t=await r();if(!t)return e;try{let n=t.originalPositionFor({line:e.lineNumber,column:e.columnNumber});if(n&&n.source)return{functionName:e.functionName,fileName:n.source,lineNumber:n.line||e.lineNumber,columnNumber:n.column||e.columnNumber}}catch{}return e},a}function s(e,t=6e4){return e&&e.length>t?e.slice(0,t)+`...<truncated>`:e}async function c(t,r){if(!r)return t;try{let i=await n();if(!i)return t;let{StackTrace:s,StackTraceGPS:c}=i,l=Error(t);try{l.stack=r}catch{}try{s.getSource&&=()=>Promise.resolve(``),s._getSource&&=()=>Promise.resolve(``)}catch{}let u=await s.fromError(l,{offline:!0}).catch(()=>[]);if(!Array.isArray(u)||!u.length)return t;let d=o(c,await a()),f=[];for(let t of u){let n=t;if(d)try{if(n=await d.pinpoint(t).catch(()=>t),n.functionName===`react_stack_bottom_frame`)break}catch(r){e.log(`Stack trace mapping failed`,r),n=t}let r=n.functionName||t.functionName||`<anonymous>`,i=n.fileName||n.source||t.fileName||`<unknown>`,a=n.lineNumber||t.lineNumber||0,o=n.columnNumber||t.columnNumber||0;f.push(` at ${r} (${i}:${a}:${o})`)}return f.length?t+`
8
-
9
- Parsed & Mapped Stack:
10
- `+f.join(`
11
- `):t}catch(n){return e.log(`Stack parsing/mapping failed`,n),t}}}function v(){let e=document.getElementById(`root`);if(!e||!window.bw)return;let t=()=>{window.bw?.request({type:`REPORT_HEIGHT`,height:Math.ceil(e.getBoundingClientRect().height)}).catch(()=>{})};try{new ResizeObserver(t).observe(e)}catch{}window.addEventListener(`load`,t)}function y(){let e=()=>{for(let e of[document.documentElement,document.body]){if(!e)continue;let t=getComputedStyle(e).backgroundColor;if(t&&t!==`transparent`&&t!==`rgba(0, 0, 0, 0)`)return t}return null},t,n=()=>{let n=e();n!==t&&(t=n,window.bw?.request({type:`REPORT_BACKGROUND`,color:n}).catch(()=>{}))},r=()=>{let e=new MutationObserver(n);e.observe(document.documentElement,{attributes:!0}),document.body&&e.observe(document.body,{attributes:!0}),n()};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,r,{once:!0}):r(),window.addEventListener(`load`,n)}let b=o?`<script type="module">(${y.toString()})();<\/script>`:``,x=`<script type="module">(${m.toString()})(window);<\/script>`,S=[`<script type="module">(${_.toString()})();<\/script>`,`<script type="module">window.bw = (${l.toString()})(${s.toString()});<\/script>`,`<script type="module">window.data = ${c.toString()};<\/script>`,`<script type="module">window.bw.formDataToObject = window.data;<\/script>`,`<script type="module">window.bw.base64ToStr = ${g.toString()};<\/script>`,`<script type="module">window.bw.locale = ${JSON.stringify(a??`en`)};<\/script>`,x,b,...i?[`<script type="module">(${v.toString()})();<\/script>`]:[]].join(`
12
- `),C=i?`height: auto;`:`height: 100%;`;if(t===`react@18`||t===`react@19`){let t,n,r;typeof e==`object`?(t=h(e.js),n=e.css,r=e.sourcemap):t=h(e);let i=r&&u?`\\n//# sourceMappingURL=${u(r)}`:``;return`
13
- <!DOCTYPE html>
14
- <html lang="${a??`en`}" style="${C}">
15
- <head>
16
- <meta http-equiv="Content-Security-Policy" content="${f}">
17
- <meta charset="utf-8">
18
- ${S}
19
- <script type="module">
20
- window.__sandboxSourceMapRef = ${JSON.stringify(r??null)};
21
- const __appCode = window.bw.base64ToStr('${t}');
22
- window.__sandboxAppCode = __appCode;
23
- const codeWithName = __appCode + "\\n//# sourceURL=inline://app.js${i}";
24
- const mod = await import(URL.createObjectURL(new Blob([codeWithName], { type: 'application/javascript' })));
25
- mod.default('root', window.bw);
26
- <\/script>
27
- ${n?`<style>${n}</style>`:``}
28
- </head>
29
- <body style="${C} margin: 0;">
30
- <div id="root" style="${C}"></div>
31
- </body>
32
- </html>
33
- `}let w,T=``;if(typeof e==`string`)T=e,w=h(e);else throw Error(`Invalid bodyContent type. Expected string or object, got ${typeof e}`);return`
34
- <!DOCTYPE html>
35
- <html lang="${a??`en`}" style="height: 100%;">
36
- <head>
37
- <meta http-equiv="Content-Security-Policy" content="${f}">
38
- <meta charset="utf-8">
39
- <script type="module">(${_.toString()})();<\/script>
40
- ${x}
41
- <script type="module">
42
- const __appCode = window.bw.base64ToStr('${w}');
43
- window.__sandboxAppCode = __appCode;
44
- const codeWithName = __appCode + "\\n//# sourceURL=inline://app.js";
45
- const mod = await import(URL.createObjectURL(new Blob([codeWithName], { type: 'application/javascript' })));
46
- mod.default('root', window.bw);
47
- <\/script>
48
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1.0.2/css/bulma.min.css" />
49
- <link rel="stylesheet" href="/styles/sandbox.css" />
50
-
51
- <script>
52
- window.bw = (${l.toString()})(${s.toString()});
53
- window.data = ${c.toString()};
54
- window.bw.formDataToObject = window.data; // Expose formDataToObject as part of the \`bw\` api.
55
- window.bw.base64ToStr = ${g.toString()};
56
- window.bw.locale = ${JSON.stringify(a??`en`)};
57
- <\/script>
58
- ${b}
59
- </head>
60
- <body style="height: 100%; margin: 0;">
61
- ${T}
62
- </body>
63
- </html>
64
- `}var v=class extends MessageChannel{#e;#t;#n;#r;#i=0;#a=new Map;constructor(e){super(),this.#e=e.sandboxIframe,this.#t=e.onRequest,this.#n=e.onError,this.#r=e.getInitialRoute,this.port1.onmessage=this.#c,this.port2.onmessageerror=e=>{this.#n(Error(e.data))},this.#e.contentDocument?.readyState===`complete`&&this.#o()?queueMicrotask(this.#s):this.#e.addEventListener(`load`,this.#s,{once:!0})}request=(e,t={})=>new Promise((n,r)=>{let i=++this.#i,a=t.timeoutMs&&t.timeoutMs>0?setTimeout(()=>{this.#a.delete(i),r(Error(`Sandbox request timed out after ${t.timeoutMs}ms (${e.type})`))},t.timeoutMs):void 0;this.#a.set(i,{resolve:n,reject:r,timeoutId:a});let o={requestId:i,payload:e};this.port1.postMessage(o)});close(){this.#e.removeEventListener(`load`,this.#s);for(let[e,t]of this.#a)t.timeoutId&&clearTimeout(t.timeoutId),t.reject(Error(`Sandbox message channel closed`)),this.#a.delete(e);this.port1.close(),this.port2.close()}#o=()=>{try{let e=this.#e.contentWindow?.location.href;return!!e&&e!==`about:blank`}catch{return!1}};#s=()=>{this.#e.contentWindow?this.#e.contentWindow.postMessage({type:`INIT_CHANNEL`,initialRoute:this.#r?.()??`/`},`*`,[this.port2]):this.#n(Error(`Missing contentWindow on iframe`))};#c=async e=>{`replyTo`in e.data?this.#l(e.data):this.#u(e.data)};#l=async e=>{let t=this.#a.get(e.replyTo);t?.timeoutId&&clearTimeout(t.timeoutId),t?.resolve(e.payload),this.#a.delete(e.replyTo)};#u=async e=>{let{requestId:t,payload:n}=e;if(n.type===`ERROR`)return this.#n(Error(n.message));let r;try{let e=await this.#t(n);r={replyTo:t,payload:e?.type===`GET_UI_DATA_RESPONSE`?JSON.parse(JSON.stringify(e)):e}}catch(e){r={replyTo:t,payload:{type:`ERROR`,message:e.message}}}this.port1.postMessage(r)}},y=500,b=2e3,x=`bw-ui`,S=new Set([`error`,`fatal`]),C=new Set([`continue`,`continue_next`]);function w(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function T(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function E(e){let t=new TextDecoder().decode(T(e.base64));try{return JSON.parse(t)}catch{return t}}function D(e){return{ready:!1,mode:e,log:[],submits:[]}}function O(e,t){e.ready||(e.ready=!0,k(e,t,{kind:`ready`}))}function k(e,t,n){e.log.push(n),e.log.length>y&&e.log.shift(),n.kind===`submit`&&e.submits.push(n);let r=n.kind!==`console`||S.has(n.level.toLowerCase());n.kind!==`chrome`&&r&&t.call(`host_event`,n).catch(()=>{})}function A(e){let{init:t,transport:r,state:s,controls:c}=e,l=e=>k(s,r,e),u=e=>{if(t.mode===`detached`)throw Error(`${e} is not available in a UI-only module`)},d=()=>{if(!t.runId||!t.taskRunId)throw Error(`A headless host in run mode needs the run and the task run`);return{runId:t.runId,uiTaskRunId:t.taskRunId}},f=async(e,t)=>{try{let n=await r.call(e,t);return l({kind:`bridge`,method:e,ok:!0}),n}catch(t){throw l({kind:`bridge`,method:e,ok:!1,error:t.message}),t}},p=async e=>E(await f(`blob_get`,{key:e}));return async e=>{switch(e.type){case`INVOKE_TASK`:{let{outputs:n}=t.mode===`run`?await f(`invoke_run_task`,{...a(e,d()),timeout_seconds:e.timeout}):await f(`invoke_workblock_task`,{...i(e,t),timeout_seconds:e.timeout});return{type:`INVOKE_RESPONSE`,result:await o(n,p)}}case`SAVE_BLOB`:{let t=e.blob instanceof Blob?e.blob:new Blob([new Uint8Array(e.blob)]),{blob_ref:n}=await f(`blob_put`,{content_type:t.type||`application/octet-stream`,base64:w(new Uint8Array(await t.arrayBuffer()))});return{type:`SAVE_BLOB_RESPONSE`,blobRef:n}}case`FETCH_BLOB`:return{type:`FETCH_BLOB_RESPONSE`,blob:T((await f(`blob_get`,{key:e.blobRef})).base64)};case`GET_UI_DATA`:{let e=n(t.data)?await p(t.data):t.data;return O(s,r),e==null?{type:`GET_UI_DATA_RESPONSE`}:{type:`GET_UI_DATA_RESPONSE`,data:e}}case`SET_ACTIONS`:e.actions.length>0&&u(`Actions are`),c.setActions(e.actions);return;case`SET_SUBMIT_HANDLER`:e.present&&u(`A submit handler is`),c.setSubmitVisible(e.present);return;case`CONTINUE_UI`:if(u(`Continue is`),t.mode===`run`){l({kind:`chrome`,type:e.type});return}l({kind:`submit`,via:`continue`,data:e.inputArgs});return;case`CONSOLE_LOG`:l({kind:`console`,level:e.level,message:e.message});return;case`ERROR`:throw l({kind:`page_error`,message:e.message}),Error(`Received error from sandbox ${e.message}`);case`SUBSCRIBE_CHILD_RUNS`:return{type:`CHILD_RUNS_UPDATE`,childRuns:t.mode===`run`?t.childRuns??[]:[]};case`START_CHILD`:throw Error(`Background runs are not available in a headless UI test`);case`YJS_EMIT_EVENT`:return{type:`YJS_EMIT_EVENT_RESPONSE`,event:await f(`yjs_emit_event`,{data_key:e.dataKey,data:e.data,transient:e.transient})};case`YJS_GET_EVENTS`:return{type:`YJS_GET_EVENTS_RESPONSE`,events:await f(`yjs_get_events`,{data_key:e.dataKey})};case`YJS_SUBSCRIBE_EVENTS`:await f(`yjs_subscribe_events`,{data_key:e.dataKey});return;case`YJS_UNSUBSCRIBE_EVENTS`:await f(`yjs_unsubscribe_events`,{data_key:e.dataKey});return;case`YJS_RESET_EVENTS`:throw Error(`A headless host does not reset collaborative history`);case`GRAPHLAKE_QUERY`:case`GRAPHLAKE_SUBSCRIBE`:case`GRAPHLAKE_UNSUBSCRIBE`:throw Error(`GraphLake data is not available in a headless host`);case`OPEN_PLATFORM_CHAT`:case`CLOSE_PLATFORM_CHAT`:throw l({kind:`chrome`,type:e.type}),Error(`The platform chat is not available in a headless host`);case`CREATE_CHAT`:case`UNMOUNT_CHAT`:case`SEND_CHAT`:case`LOAD_MORE_CHAT`:case`STOP_CHAT`:case`RECONNECT_CHAT`:case`RETRY_CHAT_MESSAGE`:case`DISCARD_CHAT_MESSAGE`:case`PREPARE_CHAT_WIDGET`:case`CHAT_WIDGET_REQUEST`:case`UNMOUNT_CHAT_WIDGET`:throw Error(`Embedded chat is not available in a headless host`);case`NOTIFICATIONS_REQUEST_PERMISSION`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_PERMISSION_RESPONSE`,permission:`unsupported`};case`NOTIFICATIONS_SHOW`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_SHOW_RESPONSE`,shown:!1};case`NOTIFICATIONS_CLOSE`:case`SET_SHORTCUTS`:case`REPORT_HEIGHT`:case`REPORT_BACKGROUND`:case`NAVIGATE_TO_STREAM`:case`ROUTE_CHANGED`:case`ROUTES_CHANGED`:l({kind:`chrome`,type:e.type});return;default:return e}}}async function j(e){let{init:t,transport:n,state:r,action:i}=e,a=e=>k(r,n,e),o;try{let t=await e.request({type:`GET_DATA`});if(t.type!==`GET_DATA_RESPONSE`){a({kind:`submit`,via:`submit`,action:i,error:`Unexpected response ${t.type}`});return}if(t.data.status===`ERROR`){a({kind:`submit`,via:`submit`,action:i,error:t.data.error??`Submission rejected`});return}o=t.data.data}catch(e){a({kind:`submit`,via:`submit`,action:i,error:e.message});return}if(t.mode!==`run`){a({kind:`submit`,via:`submit`,action:i,data:o});return}try{await n.call(`continue_ui`,{task_id:t.taskRunId,data:o}),a({kind:`submit`,via:`submit`,action:i,data:o,sent:!0})}catch(e){a({kind:`submit`,via:`submit`,action:i,data:o,sent:!1,error:e.message})}}var M=`
65
- html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; }
66
- #bw-frame { height: 100%; }
67
- #bw-frame.with-controls { height: calc(100% - 52px); }
68
- #bw-frame iframe { border: 0; width: 100%; height: 100%; display: block; }
69
- #bw-controls { height: 52px; box-sizing: border-box; display: flex; gap: 8px; align-items: center; padding: 0 12px; border-top: 1px solid #e5e5e5; }
70
- #bw-controls[hidden] { display: none; }
71
- `;function N(e,t){let n=D(e.mode),r=document,i=r.createElement(`style`);i.textContent=M,r.head.appendChild(i);let a=r.createElement(`div`);a.id=`bw-frame`;let o=r.createElement(`div`);o.id=`bw-controls`,o.hidden=!0;let s=r.createElement(`button`);s.type=`button`,s.textContent=`Submit`,s.hidden=!0,o.appendChild(s),r.body.append(a,o);let c=r.createElement(`iframe`);c.name=x,c.title=`Task UI`,c.setAttribute(`sandbox`,`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-top-navigation-by-user-activation`),c.srcdoc=_({content:e.bundle,runtime:e.runtime,csp:e.csp,locale:e.locale??`en`}),c.addEventListener(`load`,()=>setTimeout(()=>O(n,t),b),{once:!0}),a.appendChild(c);let l=[],u=()=>{let e=!s.hidden||l.length>0;o.hidden=!e,a.classList.toggle(`with-controls`,e)},d=e=>k(n,t,e),f=new v({sandboxIframe:c,onRequest:A({init:e,transport:t,state:n,controls:{setSubmitVisible:e=>{s.hidden=!e,u()},setActions:e=>{l.forEach(e=>e.remove()),l=e.map(e=>{let t=r.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled??!1,t.onclick=()=>{if(C.has(e.key)){p(e.key);return}f.request({type:`ON_ACTION`,key:e.key}).catch(e=>{d({kind:`page_error`,message:e.message})})},o.appendChild(t),t}),u()}}}),onError:e=>d({kind:`page_error`,message:e.message})}),p=r=>j({init:e,transport:t,state:n,action:r,request:e=>f.request(e,{timeoutMs:3e4})});return s.onclick=()=>void p(),t.subscribe(e=>{let t=e.type===`yjs_event`?`__yjs_event__`:`__yjs_events_reset__`;f.request({type:`ON_EVENT`,event:t,data:e.data}).catch(()=>{})}),n}function P(e){return{call:(t,n)=>e(t,n),subscribe:()=>{}}}function F(e,t){return{call:async(t,n)=>{let r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({method:t,body:n})}),i={};try{i=await r.json()}catch{throw Error(`Bridge call ${t} failed with HTTP status ${r.status}`)}if(!r.ok||!i.ok)throw Error(i.error??`Bridge call ${t} failed with HTTP status ${r.status}`);return i.result},subscribe:e=>{if(!t)return;let n=new EventSource(t);n.onmessage=t=>{e(JSON.parse(t.data))}}}}var I=document.currentScript?.dataset??{};function L(){if(typeof window.bwTransport==`function`)return P(window.bwTransport);if(I.bridgeUrl)return F(I.bridgeUrl,I.eventsUrl);throw Error(`The headless host has no transport: define window.bwTransport or data-bridge-url`)}var R={start(e){if(R.state)throw Error(`The headless host already started`);return R.state=N(e,L()),R.state}};window.bwHeadlessHost=R,I.initUrl&&fetch(I.initUrl).then(e=>{if(!e.ok)throw Error(`Loading ${I.initUrl} failed with HTTP status ${e.status}`);return e.json()}).then(e=>R.start(e)).catch(e=>{document.body.textContent=e.message,console.error(e)})})();