@beyondwork/wb-cli 0.1.28 → 0.1.30

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +6 -14
  3. package/out/cli.js +257 -556
  4. package/out/extension.js +193 -861
  5. package/package.json +15 -11
  6. package/wb-cli/skills/bw-workblock/SKILL.md +69 -0
  7. package/wb-cli/skills/bw-workblock/references/browser-run.sh +103 -0
  8. package/wb-cli/skills/bw-workblock/references/browser-validation.md +46 -0
  9. package/wb-cli/skills/bw-workblock/references/validate-ui.mjs +279 -0
  10. package/out/auth.js +0 -75
  11. package/out/auth.js.map +0 -1
  12. package/out/cli.js.map +0 -1
  13. package/out/client.js +0 -117
  14. package/out/client.js.map +0 -1
  15. package/out/connection_feedback.js +0 -45
  16. package/out/connection_feedback.js.map +0 -1
  17. package/out/extension.js.map +0 -1
  18. package/out/lib/branches.js +0 -138
  19. package/out/lib/branches.js.map +0 -1
  20. package/out/lib/branches.test.js +0 -185
  21. package/out/lib/branches.test.js.map +0 -1
  22. package/out/lib/index.js +0 -29
  23. package/out/lib/index.js.map +0 -1
  24. package/out/lib/logger.js +0 -28
  25. package/out/lib/logger.js.map +0 -1
  26. package/out/lib/workblock.js +0 -470
  27. package/out/lib/workblock.js.map +0 -1
  28. package/out/lib/workblock.test.js +0 -607
  29. package/out/lib/workblock.test.js.map +0 -1
  30. package/out/lib/workspace.js +0 -282
  31. package/out/lib/workspace.js.map +0 -1
  32. package/out/lib/workspace.test.js +0 -666
  33. package/out/lib/workspace.test.js.map +0 -1
  34. package/out/lib/ws-client.test.js +0 -188
  35. package/out/lib/ws-client.test.js.map +0 -1
  36. package/out/tree_data_provider.js +0 -274
  37. package/out/tree_data_provider.js.map +0 -1
  38. package/out/types.js +0 -25
  39. package/out/types.js.map +0 -1
  40. package/out/ws-client.js +0 -466
  41. package/out/ws-client.js.map +0 -1
package/package.json CHANGED
@@ -3,17 +3,22 @@
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.28",
6
+ "version": "0.1.30",
7
+ "vsce": {
8
+ "baseContentUrl": "https://github.com/bwllaming/code/blob/HEAD/src/vscode/beyondwork",
9
+ "baseImagesUrl": "https://github.com/bwllaming/code/raw/HEAD/src/vscode/beyondwork"
10
+ },
7
11
  "icon": "media/icon.png",
8
12
  "engines": {
9
13
  "vscode": "^1.94.0",
10
- "node": ">=16.0.0"
14
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
11
15
  },
12
16
  "categories": [
13
17
  "Other"
14
18
  ],
15
19
  "bin": {
16
- "beyondwork": "./out/cli.js"
20
+ "beyondwork": "./out/cli.js",
21
+ "wb-cli": "./out/cli.js"
17
22
  },
18
23
  "activationEvents": [
19
24
  "onView:beyondworkConnections",
@@ -31,6 +36,7 @@
31
36
  ],
32
37
  "files": [
33
38
  "out/**/*",
39
+ "wb-cli/skills/bw-workblock/**",
34
40
  "media/icon.png",
35
41
  "CHANGELOG.md",
36
42
  "README.md",
@@ -138,24 +144,22 @@
138
144
  "file-type": "^21.3.3",
139
145
  "glob": "^11.1.0",
140
146
  "ignore": "^7.0.3",
141
- "markdown-it": "^14.2.0",
147
+ "markdown-it": "^14.3.2",
142
148
  "mime-types": "^2.1.35",
143
149
  "mocha": "^10.8.2",
144
150
  "node-fetch-cache": "^5.1.0",
145
151
  "uuid": "^11.0.3",
146
152
  "ws": "^8.21.1",
147
- "yaml": "^2.8.3"
153
+ "yaml": "^2.9.1"
148
154
  },
149
155
  "scripts": {
150
- "compile": "pnpm run check-types && node esbuild.js --production && pnpm run build-webview",
156
+ "compile": "pnpm run check-types && node esbuild.js --production",
151
157
  "check-types": "tsc --noEmit",
152
- "watch": "tsc -watch -p ./",
158
+ "watch": "node esbuild.js --watch",
153
159
  "watch:esbuild": "node esbuild.js --watch",
154
160
  "watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
155
- "package": "pnpm run check-types && node esbuild.js --production && pnpm run build-webview",
161
+ "package": "pnpm run check-types && node esbuild.js --production",
156
162
  "vsix": "bazel build //src/vscode/beyondwork:package",
157
- "build-webview": "esbuild ./src/webview/main.ts --bundle --outfile=extension/out/webview/main.js --format=iife --platform=browser",
158
- "build-lib": "tsc -p tsconfig.json",
159
- "test": "pnpm run build-lib && mocha 'out/lib/**/*.test.js'"
163
+ "test": "pnpm run check-types && node esbuild.js --tests && mocha 'out/lib/**/*.test.js'"
160
164
  }
161
165
  }
@@ -0,0 +1,69 @@
1
+ ---
2
+ name: bw-workblock
3
+ description: Create or edit a Beyond Work workblock that lives on a tenant, from a coding agent session, with `wb-cli`. Use whenever the user asks to create, change, fix, extend, inspect, run or validate a workblock on a tenant, names a Studio URL (https://<tenant>/w/studio/detail/<id> or /w/studio/s/<id>) or a workblock id, or wants a change pushed to a workblock version. Covers credentials, create/clone/pull/push, validation, unit tests, runs, versions, and where the authoring knowledge (skills, docs) lands in the checkout.
4
+ ---
5
+
6
+ # bw-workblock
7
+
8
+ `wb-cli` (the npm package `@beyondwork/wb-cli`) turns a workblock on a tenant into local files and
9
+ saves them back the way Studio's Save and Update do. In the Beyond Work monorepo, call the wrapper by
10
+ its path, `<monorepo>/bin/wb-cli`, wherever this skill says `wb-cli`, and put checkouts outside the
11
+ monorepo. `clone` and `create` write the checkout to the directory you give them. Every other verb
12
+ acts on the checkout that holds the current directory, so run it from there. The request is the whole
13
+ job, push and publish included: do not stop to ask. Deploying a workblock version to `main` must be
14
+ done from Studio.
15
+
16
+ ## The loop
17
+
18
+ 1. **Get the files.** `wb-cli clone <studio-url> <dir>`, or `wb-cli create <tenant-host>
19
+ "<name>" <dir>` for a new workblock. The checkout is a git repository that wb-cli commits to:
20
+ HEAD is the server's state after the last clone, pull or push, so `git status` lists your
21
+ unpushed edits, new files included, and `git diff HEAD` shows the edits to files the server
22
+ already had. `.bw/workblock.json` binds it to the platform; do not edit it.
23
+ 2. **Read before writing.** `AGENTS.md`, then the `.skills/` entries for the area you touch, then
24
+ `.docs/docs.md` for each platform API you call. The platform changes faster than your memory of
25
+ it, and validation catches only part of what the docs would have told you.
26
+ 3. **Design the experience** of every new workblock and module before you write code: read
27
+ `.skills/workblock-architecture`, choose the pattern, and decide who starts each module and what a
28
+ person sees at the start, during input, while it runs and at the result. A module that a person
29
+ starts begins with a task that shows a UI and has no module inputs: for a module with inputs,
30
+ Studio's Start opens a generic "Configure & Run module" form with one raw field per input.
31
+ 4. **Edit.** A test is an entry under the module's `tests:` (`name`, `type: pytest`) plus
32
+ `<module>/tests/<name>.py`. A task's code reaches a test as a pytest fixture, not as a module to
33
+ import: `def test_x(flag_gaps): assert flag_gaps.flag(...)` gets task "Flag Gaps", the parameter
34
+ being the task name in lower case with spaces replaced by underscores. A file no manifest entry
35
+ claims is not pushed. Change only what the request asks for: no fixes to nearby
36
+ tasks, no tidying of files you did not need to touch, and no tasks beyond the request and the
37
+ experience of step 3.
38
+ 5. **Validate** with `wb-cli validate` until it reports no errors. Warnings are advisory.
39
+ 6. **Publish** with `wb-cli push --update` (`push --new-version <name> --update` from a `main`
40
+ checkout). Without `--update`, or when the CLI reports the push as not published, the version
41
+ stays behind, and a deploy in Studio would ship it without your change.
42
+ 7. **Prove it.** Run `wb-cli test [<module>]` when the module has tests, then `wb-cli run
43
+ <module>`, or `wb-cli run <module>/<task> --inputs '{...}'`, for what you changed. A run never
44
+ passes through Studio's Start and stops at a task UI. From a monorepo checkout, on a tenant on the
45
+ dev-eu1 cluster, you can also drive a UI in a browser from Start to the result, as
46
+ `references/browser-validation.md` next to this file describes; it is optional, and anywhere else
47
+ it is not possible. What you did not see run, report as not checked.
48
+ 8. **Report** the Studio workspace URL, the version, the files changed, the validate, test, run and
49
+ browser results or why there were none, and what is left for the user in Studio.
50
+
51
+ ## Credentials
52
+
53
+ `wb-cli login <host>` checks the tenant's token in `~/.config/beyondwork/credentials.json` and
54
+ prints the user it belongs to; when there is none, it says what to ask the user for. You never
55
+ handle the token: do not open the credentials file, source an environment file that holds one, ask
56
+ for it, or put it in a command, because your transcript and the shell history are kept.
57
+
58
+ ## Branches
59
+
60
+ `main` is what is deployed; the CLI never writes it, and it is empty until the first deploy. A
61
+ version `features/<name>` holds what was published with Update; each Studio workspace saves to its
62
+ own `features/<name>@stream/<workspace-id>`. To continue work someone left in a workspace, clone the
63
+ workspace URL (`wb-cli branches <studio-url>` lists them); cloning `features/<name>` gives only
64
+ the published state. When the CLI refuses a push or a pull (exit 3), its message names the remedy.
65
+
66
+ ## Row store
67
+
68
+ Workblock-scoped rows are shared by `main`, every version and every workspace of the workblock, so a
69
+ test that writes rows uses keys of its own and never resets the store.
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env bash
2
+ # The browser-validation recipe as one script, run from inside the workblock checkout:
3
+ # REPO=<monorepo> MODULE=<module> SCRIPT=<path>/validate-ui.mjs SHOTS_DIR=<dir> bash browser-run.sh
4
+ # START=studio (the default) presses the module's Start button in the browser, the way a person
5
+ # does. START=cli starts the run with `wb-cli run <module>` instead, for a module that people never
6
+ # start from Studio (a trigger, a schedule or another workblock starts it).
7
+ # Every step is one shell, so the session cookie never lives in an exported variable.
8
+ # Exit codes: 0 submitted and outputs printed; 1 setup or run problem (the message says which);
9
+ # 3 the run failed or still waits at a UI nobody drove; validate-ui.mjs's own 2 (login or page),
10
+ # 3 (submit rejected, or Start opened the generic input form) and 4 (no task UI) pass through, and
11
+ # its 5 (a UI with its own actions, left open) ends the recipe with the run waiting there, exit 0.
12
+ set -euo pipefail
13
+ : "${REPO:?the monorepo checkout}" "${MODULE:?the module to run}" "${SCRIPT:?validate-ui.mjs}" "${SHOTS_DIR:?screenshot directory}"
14
+ START=${START:-studio}
15
+ case "$START" in studio | cli) ;; *) echo "START is studio or cli, not $START" >&2; exit 1 ;; esac
16
+ W="$REPO/bin/wb-cli"
17
+
18
+ # 1. The tenant host and the workspace URL of this checkout.
19
+ STATUS=$("$W" status --json)
20
+ HOST=$(jq -r .marker.host <<<"$STATUS")
21
+ WORKSPACE_URL="https://$HOST/w/studio/s/$(jq -r .marker.streamId <<<"$STATUS")"
22
+
23
+ # 2. testcookies inputs. -t is the host's first label (testcookies builds the cookie domain
24
+ # <t>.dev-eu1.bworker.ai from it, so the tenant must be on dev-eu1). -n is the Kubernetes
25
+ # namespace of the tenant's ingress. -e is the user the wb-cli token belongs to. kubectl
26
+ # runs with the monorepo's environment, which holds the kubeconfig.
27
+ TENANT=${HOST%%.*}
28
+ NS=$(cd "$REPO" && eval "$(DIRENV_LOG_FORMAT= direnv export bash 2>/dev/null)" && kubectl --context dev-eu1 get ingress -A \
29
+ -o jsonpath='{range .items[*]}{.metadata.namespace}{" "}{.spec.rules[*].host}{"\n"}{end}' 2>/dev/null |
30
+ awk -v h="$HOST" '{for (i = 2; i <= NF; i++) if ($i == h) { print $1; exit }}') || true
31
+ [ -n "$NS" ] || { echo "No ingress on dev-eu1 serves $HOST: the tenant is not on dev-eu1, or kubectl has no access. Report the UI as not checked in a browser." >&2; exit 1; }
32
+ EMAIL=$("$W" login "$HOST" --json | jq -r .user)
33
+ echo "host=$HOST tenant=$TENANT namespace=$NS email=$EMAIL workspace=$WORKSPACE_URL"
34
+
35
+ # 3. Mint the cookie into a private file. Never print it. A Forbidden here means the tenant's
36
+ # secret is not readable with your credentials: that is the stop to report.
37
+ COOKIE_FILE=$(umask 077 && mktemp)
38
+ trap 'rm -f "$COOKIE_FILE"' EXIT
39
+ COOKIE_ERR=$(mktemp)
40
+ if ! (cd "$REPO" && bin/bazel run //src/beyondwork.ai/tools/testcookies:testcookies -- \
41
+ -n "$NS" -t "$TENANT" -e "$EMAIL" >"$COOKIE_FILE" 2>"$COOKIE_ERR"); then
42
+ grep -i -m 3 'forbidden\|denied\|error' "$COOKIE_ERR" >&2 || tail -n 3 "$COOKIE_ERR" >&2
43
+ rm -f "$COOKIE_ERR"
44
+ echo "testcookies failed; the UI cannot be checked in a browser with these credentials. Report that." >&2
45
+ exit 1
46
+ fi
47
+ rm -f "$COOKIE_ERR"
48
+ [ -s "$COOKIE_FILE" ] || { echo "testcookies wrote no cookie" >&2; exit 1; }
49
+
50
+ # 4. With START=studio the browser starts the run. A run that still waits would show its UI before
51
+ # Start is pressed, so stop it first, as `run` does. With START=cli the run starts here and must
52
+ # report "waiting"; anything else is a task problem to fix first.
53
+ if [ "$START" = studio ]; then
54
+ "$W" cancel
55
+ RUN_ID=latest
56
+ START_MODULE=$MODULE
57
+ else
58
+ RUN=$("$W" run "$MODULE" --json) || true
59
+ [ "$(jq -r .status <<<"$RUN")" = waiting ] || { echo "run did not reach the UI:" >&2; echo "$RUN" >&2; exit 1; }
60
+ RUN_ID=$(jq -r .run_id <<<"$RUN")
61
+ START_MODULE=
62
+ echo "run $RUN_ID is waiting at $(jq -r '.tasks[] | select(.task_id == "'"$(jq -r .waiting_task_id <<<"$RUN")"'") | .task_name' <<<"$RUN")"
63
+ fi
64
+
65
+ # 5. Drive each UI the run shows, one validate-ui.mjs call per UI, until the run stops waiting.
66
+ # Right after a submit the run can still report the submitted UI as waiting; when no further
67
+ # UI appears (exit 4 after the first), the run has gone past it. bin/node needs WORKSPACE_ROOT
68
+ # when the current directory is outside the monorepo.
69
+ STEP=1
70
+ OPEN=
71
+ while :; do
72
+ CODE=0
73
+ WB_WORKSPACE_URL="$WORKSPACE_URL" BW_SAML_COOKIE_FILE="$COOKIE_FILE" SHOTS_DIR="$SHOTS_DIR" BW_REPO="$REPO" \
74
+ WB_START_MODULE="$START_MODULE" WB_UI_STEP="$STEP" WORKSPACE_ROOT="$REPO" "$REPO/bin/node" "$SCRIPT" || CODE=$?
75
+ if [ "$CODE" -eq 5 ]; then
76
+ OPEN=1
77
+ break
78
+ fi
79
+ if [ "$CODE" -ne 0 ]; then
80
+ { [ "$CODE" -eq 4 ] && [ "$STEP" -gt 1 ]; } || exit "$CODE"
81
+ break
82
+ fi
83
+ [ "$("$W" run --wait-for "$RUN_ID" --json | jq -r .status)" = waiting ] || break
84
+ STEP=$((STEP + 1))
85
+ START_MODULE=
86
+ [ "$STEP" -le 10 ] || { echo "The run still waits after 10 UIs; stopping." >&2; exit 1; }
87
+ done
88
+
89
+ # 6. The outputs are the proof. A run that waits at a UI nobody drove has not reached its result;
90
+ # one that waits at the UI left open is an app doing its job.
91
+ "$W" run --wait-for "$RUN_ID"
92
+ if [ -z "$OPEN" ] && [ "$("$W" run --wait-for "$RUN_ID" --json | jq -r .status)" = waiting ]; then
93
+ echo "The run still waits for a person that no UI step drove: the recipe did not reach the result." >&2
94
+ exit 3
95
+ fi
96
+
97
+ # 7. The end of the run as Studio shows it: the graph, and the module's outputs behind its output
98
+ # node. A failure here leaves the proof of step 6 standing, so it does not fail the recipe.
99
+ if [ -z "$OPEN" ]; then
100
+ WB_WORKSPACE_URL="$WORKSPACE_URL" BW_SAML_COOKIE_FILE="$COOKIE_FILE" SHOTS_DIR="$SHOTS_DIR" BW_REPO="$REPO" \
101
+ WB_RESULT="$MODULE" WORKSPACE_ROOT="$REPO" "$REPO/bin/node" "$SCRIPT" ||
102
+ echo "No screenshot of the end of the run. Report the result view as not checked." >&2
103
+ fi
@@ -0,0 +1,46 @@
1
+ # Browser validation from Start to the result (optional, dev tenants only)
2
+
3
+ `bin/wb-cli run` proves Python tasks by their outputs. It never passes through Studio's Start and it
4
+ parks at a task UI, so what a person sees, from Start through every UI to the result, is proven only
5
+ in a browser. This check is optional. It works only on a tenant on the dev-eu1 cluster whose
6
+ namespace secrets you can read, because it mints the session cookie with `testcookies`; on any
7
+ other tenant, report the UI as not checked and hand over the workspace URL.
8
+
9
+ ## When
10
+
11
+ Worth doing for a new workblock or module that a person starts, a change to such a module's inputs
12
+ or first task, a change to a task UI (the component, its `render_ui` call, the data it shows or the
13
+ outputs it returns), and a run of the module you changed that reports `waiting`. "Should work" from
14
+ the code or the type check is a guess: say what you saw and what you did not.
15
+
16
+ When the script stops for the tenant or the access, report the UI as not checked and hand over the
17
+ workspace URL. Do not probe the access with `kubectl` yourself: a call against another context says
18
+ `Forbidden` for reasons of its own.
19
+
20
+ ## How
21
+
22
+ `browser-run.sh` next to this file does every step in one shell; `validate-ui.mjs` is the Playwright
23
+ script it runs. Copy both next to your checkout (not into it: the checkout lists files it does not
24
+ claim).
25
+
26
+ 1. Edit `useTheUi()` in your copy: fill the fields, press the buttons and wait for the texts the
27
+ request describes, with `shot(page, "<name>")` at each step.
28
+ 2. Push, then run from inside the checkout:
29
+ ```bash
30
+ REPO=<monorepo> MODULE=<module> SCRIPT=<dir>/validate-ui.mjs SHOTS_DIR=<dir>/shots \
31
+ bash <dir>/browser-run.sh
32
+ ```
33
+ It mints the session cookie into a private file, presses the module's Start button as a person
34
+ does, drives each UI the run shows and submits it (a UI with its own actions has no Submit:
35
+ press the one that continues the run in `useTheUi`, or it is left open), and prints the run's
36
+ final states and outputs.
37
+ Every stop prints what to do.
38
+ 3. Look at every screenshot in `SHOTS_DIR`: a red-on-red label or a hidden button is in the picture
39
+ and nowhere else. The `result-*` screenshots show the end of the run in Studio, where module
40
+ outputs are raw data; a Space does not show them at all (`.skills/workblock-architecture`).
41
+ Compare the outputs with what the request asked for.
42
+ 4. When something is wrong, fix it in the checkout, push, and run the script again. After three
43
+ rounds on the same problem, stop and report what still fails and what you tried.
44
+
45
+ Report what you did in the browser, which screenshots you looked at, the outputs set against the
46
+ request, and anything you could not check and why.
@@ -0,0 +1,279 @@
1
+ // validate-ui.mjs: start a module with Studio's Start button, drive its task UI in the
2
+ // workspace, submit it, and prove the submit landed. Copy it next to your checkout, edit useTheUi(), and run:
3
+ //
4
+ // WORKSPACE_ROOT=<repo> <repo>/bin/node validate-ui.mjs
5
+ //
6
+ // with these environment variables:
7
+ // BW_REPO the monorepo checkout; @playwright/test is loaded from its src/ts/neui
8
+ // (default: WORKSPACE_ROOT)
9
+ // WB_WORKSPACE_URL https://<tenant-host>/w/studio/s/<workspace-id>, from `bin/wb-cli status`
10
+ // (not the /w/studio/detail/<id> page: that one shows no task UI)
11
+ // BW_SAML_COOKIE_FILE file that holds the testcookies output (chmod 600; never print it)
12
+ // SHOTS_DIR where the screenshots go (default: ./shots)
13
+ // WB_START_MODULE the module to start with Studio's Start button, the way a person does;
14
+ // leave it unset when a run already waits at the UI (`bin/wb-cli run`)
15
+ // WB_UI_STEP which UI of the run this is, 1 for the first; useTheUi gets it
16
+ // WB_RESULT the module that ran, after the run has ended: drive no UI, and screenshot
17
+ // the end of the run as Studio shows it, that module's graph and outputs.
18
+ // Run it from the checkout, whose manifest.yaml gives the module's id.
19
+ //
20
+ // Exit codes: 0 submitted or closed, 5 left open (a UI with its own actions and no Submit),
21
+ // 2 login or page problem, 3 submit rejected or Start opened the generic input form, 4 no task
22
+ // UI appeared (with WB_RESULT: no graph appeared), 1 anything else.
23
+ // After exit 0, read the outputs: from the checkout, `bin/wb-cli run --wait-for latest`.
24
+
25
+ import { createRequire } from 'node:module';
26
+ import fs from 'node:fs';
27
+ import path from 'node:path';
28
+
29
+ const resultModule = process.env.WB_RESULT;
30
+ const resultMode = Boolean(resultModule);
31
+ const shotsDir = path.resolve(process.env.SHOTS_DIR ?? 'shots');
32
+ fs.mkdirSync(shotsDir, { recursive: true });
33
+ // The result screenshots have fixed names: remove an earlier run's before anything can fail, so
34
+ // none of them passes for this run's.
35
+ if (resultMode) {
36
+ for (const file of fs.readdirSync(shotsDir)) {
37
+ if (/^result-.*\.png$/.test(file)) fs.rmSync(path.join(shotsDir, file));
38
+ }
39
+ }
40
+
41
+ // NODE_PATH does not apply to ESM `import`, so load Playwright through require from neui.
42
+ const repo = process.env.BW_REPO ?? process.env.WORKSPACE_ROOT;
43
+ if (!repo) throw new Error('Set BW_REPO (or WORKSPACE_ROOT) to the monorepo checkout.');
44
+ const require = createRequire(path.join(repo, 'src/ts/neui/package.json'));
45
+ let chromium;
46
+ try {
47
+ ({ chromium } = require('@playwright/test'));
48
+ } catch {
49
+ console.error(`Playwright is not installed in ${repo}/src/ts. Run \`cd ${repo}/src/ts && ../../bin/pnpm install --frozen-lockfile\`, then this again.`);
50
+ process.exit(1);
51
+ }
52
+ // Installing the packages does not fetch the browser; this does, at the version the package expects.
53
+ const installBrowser = `cd ${repo}/src/ts/neui && ../../../bin/pnpm exec playwright install chromium`;
54
+
55
+ const url = process.env.WB_WORKSPACE_URL;
56
+ const cookieFile = process.env.BW_SAML_COOKIE_FILE;
57
+ const startModule = process.env.WB_START_MODULE;
58
+ const uiStep = Number(process.env.WB_UI_STEP ?? '1');
59
+ if (!url || !cookieFile) throw new Error('Set WB_WORKSPACE_URL and BW_SAML_COOKIE_FILE.');
60
+ const host = new URL(url).hostname;
61
+ // Studio opens a workspace on the entrypoint module's graph. The result pass opens the graph of
62
+ // the module that ran instead, found in the checkout's manifest by its name.
63
+ const pageUrl = resultMode ? moduleGraphUrl(resultModule) : url;
64
+ const cookie = fs.readFileSync(cookieFile, 'utf8').trim();
65
+ if (!cookie) throw new Error(`${cookieFile} is empty: mint the cookie again with testcookies.`);
66
+
67
+ let shots = 0;
68
+ async function shot(page, name) {
69
+ const prefix = resultMode ? 'result' : `ui${uiStep}`;
70
+ const file = path.join(shotsDir, `${prefix}-${String(++shots).padStart(2, '0')}-${name}.png`);
71
+ await page.screenshot({ path: file });
72
+ console.log(`screenshot ${file}`);
73
+ }
74
+
75
+ // ---- Edit this: use the UI the way the user would. `ui` is the component inside
76
+ // iframe[srcdoc]; buttons such as Submit are on `page`, outside the iframe. A run that shows
77
+ // several UIs calls this once for each, with `step` 1, 2, …: branch on it. ----
78
+ async function useTheUi(page, ui, step) {
79
+ await ui.getByLabel('Name').fill('Grace');
80
+ await shot(page, 'filled');
81
+ await ui.getByRole('button', { name: 'Shout' }).click();
82
+ await ui.getByText('GRACE!').waitFor();
83
+ await shot(page, 'after-shout');
84
+ }
85
+
86
+ // Presses Start as a person does. Returns 0 when a task UI appears, 2 when Start is missing,
87
+ // 3 when it opens the "Configure & Run module" form (a finding, not a step), 4 when nothing appears.
88
+ async function pressStart(page, moduleName) {
89
+ const named = page.getByRole('button', { name: `Start ${moduleName}`, exact: true });
90
+ const tryChanges = page.getByRole('button', { name: 'Try changes', exact: true });
91
+ const menu = page.getByRole('button', { name: 'Start specific module', exact: true });
92
+ try {
93
+ await named.or(tryChanges).or(menu).first().waitFor({ timeout: 60_000 });
94
+ } catch {
95
+ await shot(page, 'no-start-button');
96
+ console.error(`No Start button for module "${moduleName}" after 60 s. Check the module name and that the workblock validates.`);
97
+ return 2;
98
+ }
99
+ await shot(page, 'before-start');
100
+ if (await named.isVisible()) {
101
+ await named.click();
102
+ } else if (await menu.isVisible()) {
103
+ await menu.click();
104
+ // The entrypoint's item also carries an "entry" badge, so match the name's own text.
105
+ await page.getByRole('menuitem').filter({ has: page.getByText(moduleName, { exact: true }) }).click();
106
+ } else {
107
+ await tryChanges.click();
108
+ }
109
+ // The loser of the race times out later; both branches settle, so neither rejects unhandled.
110
+ const outcome = await Promise.race([
111
+ page.getByRole('dialog', { name: 'Configure & Run module' }).waitFor({ timeout: 60_000 }).then(() => 'form', () => 'timeout'),
112
+ page.locator('iframe[srcdoc]').first().waitFor({ timeout: 60_000 }).then(() => 'ui', () => 'timeout'),
113
+ ]);
114
+ if (outcome === 'form') {
115
+ await shot(page, 'start-input-form');
116
+ console.error(
117
+ `Start opened the generic "Configure & Run module" form: module "${moduleName}" has inputs, so a person who presses Start types raw values before any task UI. Give the module a first task with a UI and no module inputs, or set START=cli when people never start this module.`,
118
+ );
119
+ return 3;
120
+ }
121
+ if (outcome === 'timeout') {
122
+ await shot(page, 'no-task-ui');
123
+ console.error('No task UI and no input form 60 s after Start. Read the run with `bin/wb-cli run --wait-for latest`.');
124
+ return 4;
125
+ }
126
+ return 0;
127
+ }
128
+
129
+ // A module matches as `wb-cli run` matches it: by its id, its name, or the directory name that the
130
+ // checkout gives it.
131
+ function moduleGraphUrl(selector) {
132
+ const lower = (name) => name.trim().toLowerCase();
133
+ const dir = (name) =>
134
+ path.basename(name).toLowerCase().replace(/[^a-z0-9.-]+/g, '_').replace(/^_+|_+$/g, '').replace(/^\.+/, '');
135
+ const { modules = [] } = require('yaml').parse(fs.readFileSync('manifest.yaml', 'utf8'));
136
+ const module = modules.find(
137
+ (m) => m.id === selector || lower(m.name) === lower(selector) || dir(m.name) === dir(selector),
138
+ );
139
+ if (!module) throw new Error(`No module "${selector}" in ./manifest.yaml. Run this from the checkout.`);
140
+ const graph = new URL(url);
141
+ graph.searchParams.set('v', 'graph');
142
+ graph.searchParams.set('m', module.id);
143
+ return graph.href;
144
+ }
145
+
146
+ // Screenshots the end of the run as Studio shows it: the graph, then the dialog that the module's
147
+ // output node opens, which lists every module output as raw data. A Space shows neither; there a
148
+ // person sees only the task UIs.
149
+ async function showResult(page) {
150
+ try {
151
+ await page.locator('.react-flow__node').first().waitFor({ timeout: 60_000 });
152
+ } catch {
153
+ await shot(page, 'no-graph');
154
+ console.error('No graph 60 s after the page loaded. Report the result view as not checked.');
155
+ return 4;
156
+ }
157
+ // Fit the whole graph, output node included, into the screenshot.
158
+ await page.getByRole('button', { name: 'fit view' }).click({ timeout: 5_000 }).catch(() => {});
159
+ await page.waitForTimeout(1_000);
160
+ await shot(page, 'graph');
161
+ const outputNode = page.locator('.react-flow__node-moduleOutput').first();
162
+ if ((await outputNode.count()) === 0) {
163
+ console.log('The module has no outputs: a person sees only its task UIs.');
164
+ return 0;
165
+ }
166
+ // The node's title button, pressed from the keyboard: Studio's floating graph toolbar can cover
167
+ // the node and take a mouse click.
168
+ await outputNode.getByRole('button').first().press('Enter');
169
+ const dialog = page.getByRole('dialog');
170
+ await dialog.waitFor();
171
+ // The values render in an editor that loads after the dialog opens; an output without a value
172
+ // shows none, so a timeout here still takes the screenshot.
173
+ await dialog.locator('.monaco-editor .view-lines').first().waitFor({ timeout: 15_000 }).catch(() => {});
174
+ await page.waitForTimeout(1_000);
175
+ await shot(page, 'outputs');
176
+ return 0;
177
+ }
178
+
179
+ let browser;
180
+ try {
181
+ browser = await chromium.launch();
182
+ } catch (e) {
183
+ if (!String(e?.message).includes("Executable doesn't exist")) throw e;
184
+ console.error(`Playwright's Chromium is not installed. Run \`${installBrowser}\`, then this again.`);
185
+ process.exit(1);
186
+ }
187
+ let exitCode = 1;
188
+ try {
189
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
190
+ await context.addCookies([
191
+ { name: '_saml_session', value: cookie, domain: host, path: '/', httpOnly: true, secure: true, sameSite: 'None' },
192
+ ]);
193
+ const page = await context.newPage();
194
+ page.setDefaultTimeout(30_000);
195
+ // Console messages of the page and of the component iframe. A rejected submit shows only
196
+ // "Submission rejected" on screen; the reason thrown by the submit handler is logged here.
197
+ const consoleLines = [];
198
+ page.on('console', (m) => {
199
+ if (m.type() === 'error' || m.type() === 'warning') consoleLines.push(`console.${m.type()}: ${m.text()}`);
200
+ });
201
+ page.on('pageerror', (e) => consoleLines.push(`pageerror: ${e.message}`));
202
+
203
+ const response = await page.goto(pageUrl);
204
+ if (response?.status() === 403) {
205
+ console.error('403 Forbidden: the cookie email is not a user of this tenant. Use the email that `bin/wb-cli login <host>` prints.');
206
+ exitCode = 2;
207
+ } else if (new URL(page.url()).hostname !== host) {
208
+ console.error(`Redirected to ${new URL(page.url()).hostname}: the cookie was rejected or expired. Mint a new one.`);
209
+ exitCode = 2;
210
+ } else if (resultMode) {
211
+ exitCode = await showResult(page);
212
+ } else {
213
+ const started = startModule ? await pressStart(page, startModule) : 0;
214
+ if (started !== 0) {
215
+ exitCode = started;
216
+ } else {
217
+ // A spinner and a read-only header show first; the component follows a few seconds later.
218
+ const frame = page.locator('iframe[srcdoc]').first();
219
+ const ui = page.frameLocator('iframe[srcdoc]').first();
220
+ try {
221
+ // The iframe is attached before the component renders into its #root: wait for both.
222
+ await frame.waitFor({ timeout: 60_000 });
223
+ await ui.locator('#root > *').first().waitFor({ timeout: 30_000 });
224
+ } catch {
225
+ await shot(page, 'no-task-ui');
226
+ console.error('No task UI after 60 s. Check that the run is still waiting (`bin/wb-cli run --wait-for latest`) and that the URL is the workspace URL.');
227
+ exitCode = 4;
228
+ }
229
+ if (exitCode !== 4) {
230
+ await shot(page, 'ui-loaded');
231
+ // Taken while the iframe is still attached: a continue action pressed in useTheUi removes
232
+ // it, and looking it up afterwards would wait out the page timeout and fail.
233
+ const frameHandle = await frame.elementHandle();
234
+ await useTheUi(page, ui, uiStep);
235
+
236
+ // Studio shows Submit unless the UI set its own actions (bw.setActions). Then a continue
237
+ // action pressed in useTheUi closes the UI, and anything else leaves it open.
238
+ const submit = page.getByRole('button', { name: 'Submit', exact: true });
239
+ // A submit handler that throws shows "Submission rejected"; a server error "Failed to submit".
240
+ const rejected = page.getByText('Submission rejected').or(page.getByText('Failed to submit')).first();
241
+ if (await submit.waitFor({ timeout: 3_000 }).then(() => true, () => false)) {
242
+ await submit.click();
243
+ // Accepted: the component's iframe goes away. Rejected: the toast.
244
+ const outcome = await Promise.race([
245
+ frameHandle.waitForElementState('hidden', { timeout: 60_000 }).then(() => 'accepted'),
246
+ rejected.waitFor({ timeout: 60_000 }).then(() => 'rejected'),
247
+ ]);
248
+ await shot(page, `submit-${outcome}`);
249
+ if (outcome === 'rejected') {
250
+ console.error('Submit rejected by the component; the reason is in the console lines below.');
251
+ exitCode = 3;
252
+ } else {
253
+ console.log('Submit accepted. Next: bin/wb-cli run --wait-for latest in the checkout.');
254
+ exitCode = 0;
255
+ }
256
+ } else {
257
+ const outcome = await Promise.race([
258
+ frameHandle.waitForElementState('hidden', { timeout: 10_000 }).then(() => 'closed', () => 'open'),
259
+ rejected.waitFor({ timeout: 10_000 }).then(() => 'rejected', () => 'open'),
260
+ ]);
261
+ await shot(page, outcome === 'open' ? 'left-open' : outcome);
262
+ if (outcome === 'rejected') {
263
+ console.error('The action pressed in useTheUi was rejected; the reason is in the console lines below.');
264
+ exitCode = 3;
265
+ } else if (outcome === 'closed') {
266
+ exitCode = 0;
267
+ } else {
268
+ console.log('No Submit button and the UI stays open: it set its own actions, and none pressed in useTheUi continued the run.');
269
+ exitCode = 5;
270
+ }
271
+ }
272
+ }
273
+ }
274
+ }
275
+ if (consoleLines.length > 0) console.error(consoleLines.map((l) => l.slice(0, 500)).join('\n'));
276
+ } finally {
277
+ await browser.close();
278
+ }
279
+ process.exit(exitCode);
package/out/auth.js DELETED
@@ -1,75 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.getApiToken = getApiToken;
37
- exports.clearApiTokens = clearApiTokens;
38
- const vscode = __importStar(require("vscode"));
39
- /**
40
- * Looks up an API token in globalState for the given host.
41
- * If not found, prompts the user to enter one and then stores it.
42
- */
43
- async function getApiToken(context, host) {
44
- // Try retrieving from globalState
45
- const storedTokens = context.globalState.get("bw_api_tokens", {});
46
- if (storedTokens && storedTokens[host]) {
47
- return storedTokens[host];
48
- }
49
- // If not found, prompt user
50
- const token = await vscode.window.showInputBox({
51
- prompt: `Enter API Token for ${host}. Create one by going into your Profile (top right) -> Settings -> API Tokens.`,
52
- placeHolder: "Example: eyJhbGciOiJIUzI1NiIsInR5cCI6...",
53
- validateInput: (value) => {
54
- if (!value || value.trim().length < 10) {
55
- return "Please enter a valid token.";
56
- }
57
- return null;
58
- },
59
- ignoreFocusOut: true,
60
- });
61
- if (!token) {
62
- return undefined;
63
- }
64
- // Save into globalState
65
- storedTokens[host] = token;
66
- context.globalState.update("bw_api_tokens", storedTokens);
67
- return token;
68
- }
69
- /**
70
- * Clears all stored API tokens from globalState.
71
- */
72
- function clearApiTokens(context) {
73
- context.globalState.update("bw_api_tokens", {});
74
- }
75
- //# sourceMappingURL=auth.js.map
package/out/auth.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,kCAkCC;AAKD,wCAEC;AA/CD,+CAAiC;AAEjC;;;GAGG;AACI,KAAK,UAAU,WAAW,CAC/B,OAAgC,EAChC,IAAY;IAEZ,kCAAkC;IAClC,MAAM,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAC1C,eAAe,EACf,EAAE,CACH,CAAC;IACF,IAAI,YAAY,IAAI,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;QACvC,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,4BAA4B;IAC5B,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC;QAC7C,MAAM,EAAE,uBAAuB,IAAI,gFAAgF;QACnH,WAAW,EAAE,0CAA0C;QACvD,aAAa,EAAE,CAAC,KAAK,EAAE,EAAE;YACvB,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,EAAE,EAAE,CAAC;gBACvC,OAAO,6BAA6B,CAAC;YACvC,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,cAAc,EAAE,IAAI;KACrB,CAAC,CAAC;IACH,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,wBAAwB;IACxB,YAAY,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IAC3B,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;IAE1D,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,SAAgB,cAAc,CAAC,OAAgC;IAC7D,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC;AAClD,CAAC"}