@thinkrun/cli 0.1.40 → 0.1.42
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/README.md +27 -0
- package/dist/bin/thinkrun.js +9 -2
- package/dist/bin/thinkrun.js.map +1 -1
- package/dist/shared/analysis-plans.d.ts +10 -0
- package/dist/shared/analysis-plans.js +12 -0
- package/dist/shared/batch-steps.d.ts +49 -0
- package/dist/shared/batch-steps.js +171 -0
- package/dist/shared/batch-steps.test.js +127 -0
- package/dist/shared/issue-report.d.ts +10 -0
- package/dist/shared/issue-report.js +126 -0
- package/dist/shared/issue-report.test.ts +110 -0
- package/dist/shared/navigation-retry.d.ts +2 -0
- package/dist/shared/navigation-retry.js +26 -0
- package/dist/shared/navigation-retry.test.js +25 -0
- package/dist/shared/onboarding-metrics.d.ts +4 -0
- package/dist/shared/onboarding-metrics.js +53 -0
- package/dist/shared/selector-hints.d.ts +1 -0
- package/dist/shared/selector-hints.js +43 -0
- package/dist/shared/selector-hints.test.js +31 -0
- package/dist/shared/slack-report.d.ts +21 -0
- package/dist/shared/slack-report.js +381 -0
- package/dist/src/adapters/local.d.ts +1 -0
- package/dist/src/adapters/local.d.ts.map +1 -1
- package/dist/src/adapters/local.js +29 -5
- package/dist/src/adapters/local.js.map +1 -1
- package/dist/src/commands/actions.d.ts +12 -0
- package/dist/src/commands/actions.d.ts.map +1 -1
- package/dist/src/commands/actions.js +102 -13
- package/dist/src/commands/actions.js.map +1 -1
- package/dist/src/commands/audit.d.ts.map +1 -1
- package/dist/src/commands/audit.js +5 -4
- package/dist/src/commands/audit.js.map +1 -1
- package/dist/src/commands/config.d.ts.map +1 -1
- package/dist/src/commands/config.js +15 -0
- package/dist/src/commands/config.js.map +1 -1
- package/dist/src/commands/install-skills.d.ts +27 -0
- package/dist/src/commands/install-skills.d.ts.map +1 -0
- package/dist/src/commands/install-skills.js +81 -0
- package/dist/src/commands/install-skills.js.map +1 -0
- package/dist/src/commands/install.d.ts.map +1 -1
- package/dist/src/commands/install.js +44 -1
- package/dist/src/commands/install.js.map +1 -1
- package/dist/src/commands/login.d.ts +3 -0
- package/dist/src/commands/login.d.ts.map +1 -0
- package/dist/src/commands/login.js +62 -0
- package/dist/src/commands/login.js.map +1 -0
- package/dist/src/commands/setup.d.ts.map +1 -1
- package/dist/src/commands/setup.js +8 -16
- package/dist/src/commands/setup.js.map +1 -1
- package/dist/src/config/store.d.ts.map +1 -1
- package/dist/src/config/store.js +1 -0
- package/dist/src/config/store.js.map +1 -1
- package/dist/src/session/account-guidance.d.ts +10 -0
- package/dist/src/session/account-guidance.d.ts.map +1 -0
- package/dist/src/session/account-guidance.js +32 -0
- package/dist/src/session/account-guidance.js.map +1 -0
- package/dist/src/session/browser-login.d.ts +6 -0
- package/dist/src/session/browser-login.d.ts.map +1 -0
- package/dist/src/session/browser-login.js +83 -0
- package/dist/src/session/browser-login.js.map +1 -0
- package/package.json +2 -1
- package/skills/thinkrun/SKILL.md +66 -0
package/README.md
CHANGED
|
@@ -4,6 +4,22 @@ CLI for ThinkRun browser automation.
|
|
|
4
4
|
|
|
5
5
|
`thinkrun` is the single CLI for controlling browsers via ThinkRun cloud and local (native host) infrastructure.
|
|
6
6
|
|
|
7
|
+
## Try ThinkRun in your own browser
|
|
8
|
+
|
|
9
|
+
You can control a Chrome tab locally before creating an account.
|
|
10
|
+
|
|
11
|
+
1. Install the [ThinkRun Chrome extension](https://chromewebstore.google.com/detail/thinkrun-screen-recorder/affbcanbhbnolapiokgjnkfjccdmefmd). With the CLI, run `thinkrun setup` to install the native host. With MCP, run `npx @thinkrun/mcp install-native-host`. Open Chrome and enable or reload the extension.
|
|
12
|
+
2. Use `thinkrun doctor` or `npx @thinkrun/mcp doctor` to check the connection. In the CLI, run `thinkrun tabs`, then `thinkrun attach <tabId>`. In MCP, ask your agent to attach to your chosen local tab.
|
|
13
|
+
3. Give the agent a small job, such as checking that a saved item is still there after reloading the page.
|
|
14
|
+
4. To save evidence, run `thinkrun login` to connect a [free ThinkRun account](https://thinkrun.ai/signup). In MCP, ask the agent to save the local session. Enable audit mode before repeating the check to capture screenshots of subsequent actions.
|
|
15
|
+
5. Open the saved session in your [Activity Feed](https://thinkrun.ai/activity). Review what happened, record feedback for your agent, or prepare a GitHub issue from the evidence you choose to share.
|
|
16
|
+
|
|
17
|
+
For a hosted browser, configure a ThinkRun API key and run `thinkrun cloud start` or select cloud mode in MCP.
|
|
18
|
+
|
|
19
|
+
### Optional onboarding metrics
|
|
20
|
+
|
|
21
|
+
To share onboarding milestones with ThinkRun, set `THINKRUN_ONBOARDING_METRICS=1` in the CLI or MCP server environment. Collection is off by default. Events contain a random installation ID, the client type, and milestones for local connection, account connection, and saving a session. Opening the generated review link can record a dashboard review using a session-specific marker. Event payloads exclude tab URLs, browser content, credentials, and account identifiers. Unset the variable or set `DO_NOT_TRACK=1` to stop sending client events.
|
|
22
|
+
|
|
7
23
|
## Requirements
|
|
8
24
|
|
|
9
25
|
- Node.js 18+ (uses native `fetch`)
|
|
@@ -230,6 +246,17 @@ appends by default, while `--clear` uses replacement semantics. Both modes rejec
|
|
|
230
246
|
missing, hidden, disabled, or non-editable targets instead of reporting success.
|
|
231
247
|
The per-character delay must be an integer from 0 through 5000 milliseconds.
|
|
232
248
|
|
|
249
|
+
### Batch
|
|
250
|
+
|
|
251
|
+
Run up to 50 actions in one call. Every step is checked first, the first failure stops the rest, and typed values are not echoed in the result.
|
|
252
|
+
|
|
253
|
+
```bash
|
|
254
|
+
thinkrun batch '[{"action":"navigate","url":"https://example.com"},{"action":"fill","selector":"input[name=q]","value":"shoes"},{"action":"press","key":"Enter"},{"action":"wait_for_text","text":"results"}]'
|
|
255
|
+
thinkrun batch --file steps.json
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Actions: `navigate` (url), `click` and `hover` (selector), `fill` and `select` (selector, value), `type` (selector, text), `press` (key), `wait` (selector or ms), `wait_for_text` (text), `evaluate` (script). Check the result before relying on later page state.
|
|
259
|
+
|
|
233
260
|
### Waiting
|
|
234
261
|
|
|
235
262
|
| Command | Description |
|
package/dist/bin/thinkrun.js
CHANGED
|
@@ -16,13 +16,14 @@ import { createAuditCommand } from '../src/commands/audit.js';
|
|
|
16
16
|
import { createResetConnectionCommand } from '../src/commands/reset-connection.js';
|
|
17
17
|
import { createInstallCommand } from '../src/commands/install.js';
|
|
18
18
|
import { createSessionDebugCommand } from '../src/commands/session-debug.js';
|
|
19
|
+
import { createLoginCommand } from '../src/commands/login.js';
|
|
19
20
|
import { createSetupCommand } from '../src/commands/setup.js';
|
|
20
21
|
import { createAnalyzeCommand } from '../src/commands/analyze.js';
|
|
21
22
|
import { createSessionsCommand } from '../src/commands/sessions.js';
|
|
22
23
|
import { createReleaseCommand } from '../src/commands/release.js';
|
|
23
24
|
import { createRecordingCommand } from '../src/commands/recording.js';
|
|
24
25
|
import { createAgentInitCommand } from '../src/commands/agent-init.js';
|
|
25
|
-
import { createNavigateCommand, createClickCommand, createClickAtCommand, createTypeCommand, createFillCommand, createScrollCommand, createWaitCommand, createWaitForTextCommand, createHoverCommand, createSelectCommand, createPressCommand, createBackCommand, createForwardCommand, createResumeCommand, createSnapshotCommand, createScreenshotCommand, createExtractCommand, createEvaluateCommand, createDialogCommand, createConsoleCommand, createNetworkCommand, createTabsCommand, createNewTabCommand, createCloseTabCommand, createAttachCommand, createUrlCommand, createTitleCommand, createHtmlCommand, createClearLogsCommand, createSwitchTabCommand, createFocusCommand, createNewWindowCommand, createTaskCommand, createTaskStatusCommand, createTaskCancelCommand, } from '../src/commands/actions.js';
|
|
26
|
+
import { createNavigateCommand, createClickCommand, createClickAtCommand, createTypeCommand, createFillCommand, createBatchCommand, createScrollCommand, createWaitCommand, createWaitForTextCommand, createHoverCommand, createSelectCommand, createPressCommand, createBackCommand, createForwardCommand, createResumeCommand, createSnapshotCommand, createScreenshotCommand, createExtractCommand, createEvaluateCommand, createDialogCommand, createConsoleCommand, createNetworkCommand, createTabsCommand, createNewTabCommand, createCloseTabCommand, createAttachCommand, createUrlCommand, createTitleCommand, createHtmlCommand, createClearLogsCommand, createSwitchTabCommand, createFocusCommand, createNewWindowCommand, createTaskCommand, createTaskStatusCommand, createTaskCancelCommand, } from '../src/commands/actions.js';
|
|
26
27
|
const __filename = fileURLToPath(import.meta.url);
|
|
27
28
|
const __dirname = dirname(__filename);
|
|
28
29
|
function resolvePackageJsonPath() {
|
|
@@ -45,7 +46,11 @@ program
|
|
|
45
46
|
.option('--json', 'Output in JSON format (default for non-TTY)')
|
|
46
47
|
.option('--quiet', 'Suppress non-error output')
|
|
47
48
|
.option('--verbose', 'Verbose output with debugging info');
|
|
48
|
-
program.addHelpText('after', '\
|
|
49
|
+
program.addHelpText('after', '\nCoding agents: run \'thinkrun install --skills\' to add the agent skill to this project.\n' +
|
|
50
|
+
'\nYour Chrome tabs: install the ThinkRun extension, run thinkrun setup and thinkrun doctor, then thinkrun tabs and thinkrun attach <tabId>.\n' +
|
|
51
|
+
' https://chromewebstore.google.com/detail/thinkrun-screen-recorder/affbcanbhbnolapiokgjnkfjccdmefmd\n' +
|
|
52
|
+
' To save and review local sessions, run thinkrun login (free account: https://thinkrun.ai/signup).\n' +
|
|
53
|
+
'\nDocs:\n' +
|
|
49
54
|
' https://thinkrun.ai/docs\n' +
|
|
50
55
|
' https://thinkrun.ai/llms.txt\n');
|
|
51
56
|
// Activate JSON mode before any command runs if --json flag is set.
|
|
@@ -57,6 +62,7 @@ program.hook('preAction', () => {
|
|
|
57
62
|
});
|
|
58
63
|
// Add commands
|
|
59
64
|
program.addCommand(createSetupCommand());
|
|
65
|
+
program.addCommand(createLoginCommand());
|
|
60
66
|
program.addCommand(createConfigCommand());
|
|
61
67
|
program.addCommand(createCloudCommand());
|
|
62
68
|
program.addCommand(createCacheCommand());
|
|
@@ -73,6 +79,7 @@ program.addCommand(createClickCommand());
|
|
|
73
79
|
program.addCommand(createClickAtCommand());
|
|
74
80
|
program.addCommand(createTypeCommand());
|
|
75
81
|
program.addCommand(createFillCommand());
|
|
82
|
+
program.addCommand(createBatchCommand());
|
|
76
83
|
program.addCommand(createPressCommand());
|
|
77
84
|
program.addCommand(createScrollCommand());
|
|
78
85
|
program.addCommand(createHoverCommand());
|
package/dist/bin/thinkrun.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thinkrun.js","sourceRoot":"","sources":["../../bin/thinkrun.ts"],"names":[],"mappings":";AAEA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,qCAAqC,CAAC;AACnF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,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AU,CAAC,iBAAiB,EAAE,CAAC,CAAC;AAExC,iBAAiB;AACjB,OAAO,CAAC,UAAU,CAAC,sBAAsB,EAAE,CAAC,CAAC;AAE7C,+CAA+C;AAC/C,OAAO,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAC,CAAC;AACxC,OAAO,CAAC,UAAU,CAAC,uBAAuB,EAAE,CAAC,CAAC;AAC9C,OAAO,CAAC,UAAU,CAAC,uBAAuB,EAAE,CAAC,CAAC;AAE9C,qBAAqB;AACrB,OAAO,CAAC,UAAU,CAAC,oBAAoB,EAAE,CAAC,CAAC;AAE3C,8BAA8B;AAC9B,OAAO,CAAC,UAAU,CAAC,qBAAqB,EAAE,CAAC,CAAC;AAE5C,0EAA0E;AAC1E,0EAA0E;AAC1E,4EAA4E;AAC5E,yEAAyE;AACzE,wEAAwE;AACxE,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAG,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAI,+BAA+B;AAC1F,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,gBAAgB,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,wCAAwC;AAEnG,kBAAkB;AAClB,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AAE5B,mCAAmC;AACnC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAClC,OAAO,CAAC,UAAU,EAAE,CAAC;AACvB,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type AnalysisPlanId = 'pro20' | 'pro40' | 'pro80';
|
|
2
|
+
export declare const ANALYSIS_PLANS: {
|
|
3
|
+
readonly [Id in AnalysisPlanId]: {
|
|
4
|
+
readonly id: Id;
|
|
5
|
+
readonly priceUsdMonthly: number;
|
|
6
|
+
readonly includedHours: number;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export declare const ANALYSIS_EXTRA_MINUTE_CENTS: 5;
|
|
10
|
+
export declare function isAnalysisPlanId(value: unknown): value is AnalysisPlanId;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Monthly analysis allowances; IDs identify the purchased offer across billing and metering. */
|
|
2
|
+
export const ANALYSIS_PLANS = Object.freeze({
|
|
3
|
+
pro20: Object.freeze({ id: 'pro20', priceUsdMonthly: 19, includedHours: 2 }),
|
|
4
|
+
pro40: Object.freeze({ id: 'pro40', priceUsdMonthly: 39, includedHours: 10 }),
|
|
5
|
+
pro80: Object.freeze({ id: 'pro80', priceUsdMonthly: 79, includedHours: 25 }),
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
export const ANALYSIS_EXTRA_MINUTE_CENTS = 5;
|
|
9
|
+
|
|
10
|
+
export function isAnalysisPlanId(value) {
|
|
11
|
+
return typeof value === 'string' && Object.prototype.hasOwnProperty.call(ANALYSIS_PLANS, value);
|
|
12
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export type BatchStep =
|
|
2
|
+
| { action: 'navigate'; url: string }
|
|
3
|
+
| { action: 'click' | 'hover'; selector: string }
|
|
4
|
+
| { action: 'fill' | 'select'; selector: string; value: string }
|
|
5
|
+
| { action: 'type'; selector: string; text: string }
|
|
6
|
+
| { action: 'press'; key: string }
|
|
7
|
+
| { action: 'wait'; selector: string; ms?: undefined }
|
|
8
|
+
| { action: 'wait'; ms: number; selector?: undefined }
|
|
9
|
+
| { action: 'wait_for_text'; text: string }
|
|
10
|
+
| { action: 'evaluate'; script: string };
|
|
11
|
+
|
|
12
|
+
export interface BatchStepResult {
|
|
13
|
+
step: number;
|
|
14
|
+
action: string;
|
|
15
|
+
success: boolean;
|
|
16
|
+
error?: string;
|
|
17
|
+
/** The step changed the page even though the batch stopped here. */
|
|
18
|
+
applied?: boolean;
|
|
19
|
+
blocked?: boolean;
|
|
20
|
+
handoffRequired?: boolean;
|
|
21
|
+
category?: string;
|
|
22
|
+
changed?: boolean;
|
|
23
|
+
matchCount?: number;
|
|
24
|
+
matchIndex?: number;
|
|
25
|
+
result?: unknown;
|
|
26
|
+
truncated?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface BatchResult {
|
|
30
|
+
success: boolean;
|
|
31
|
+
total: number;
|
|
32
|
+
completed: number;
|
|
33
|
+
failedStep?: number;
|
|
34
|
+
notRun?: number;
|
|
35
|
+
steps: BatchStepResult[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export declare const MAX_BATCH_STEPS: number;
|
|
39
|
+
export declare const MAX_BATCH_WAIT_MS: number;
|
|
40
|
+
export declare const MAX_BATCH_DURATION_MS: number;
|
|
41
|
+
export declare const BATCH_ACTIONS: string[];
|
|
42
|
+
export declare function validateBatchSteps(input: unknown):
|
|
43
|
+
| { ok: true; steps: BatchStep[] }
|
|
44
|
+
| { ok: false; error: string };
|
|
45
|
+
export declare function runBatchSteps(
|
|
46
|
+
steps: BatchStep[],
|
|
47
|
+
execute: (step: BatchStep) => Promise<unknown>,
|
|
48
|
+
options?: { maxDurationMs?: number; now?: () => number },
|
|
49
|
+
): Promise<BatchResult>;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs a fixed list of browser actions in order from a single CLI or MCP call.
|
|
3
|
+
* The whole list is validated before anything runs, and the first failure stops
|
|
4
|
+
* the rest, so a failed fill can't be followed by a submit. Results never echo
|
|
5
|
+
* typed values.
|
|
6
|
+
*/
|
|
7
|
+
export const MAX_BATCH_STEPS = 50;
|
|
8
|
+
export const MAX_BATCH_WAIT_MS = 30_000;
|
|
9
|
+
export const MAX_BATCH_DURATION_MS = 5 * 60_000;
|
|
10
|
+
const MAX_RESULT_CHARS = 4_000;
|
|
11
|
+
|
|
12
|
+
const REQUIRED_FIELDS = {
|
|
13
|
+
navigate: ['url'],
|
|
14
|
+
click: ['selector'],
|
|
15
|
+
fill: ['selector', 'value'],
|
|
16
|
+
type: ['selector', 'text'],
|
|
17
|
+
press: ['key'],
|
|
18
|
+
select: ['selector', 'value'],
|
|
19
|
+
hover: ['selector'],
|
|
20
|
+
wait_for_text: ['text'],
|
|
21
|
+
evaluate: ['script'],
|
|
22
|
+
};
|
|
23
|
+
export const BATCH_ACTIONS = [...Object.keys(REQUIRED_FIELDS), 'wait'];
|
|
24
|
+
|
|
25
|
+
function isValidUrl(value) {
|
|
26
|
+
try {
|
|
27
|
+
new URL(value);
|
|
28
|
+
return true;
|
|
29
|
+
} catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function validateStep(step, index) {
|
|
35
|
+
const label = `Step ${index + 1}`;
|
|
36
|
+
if (!step || typeof step !== 'object' || Array.isArray(step)) return `${label} must be an object.`;
|
|
37
|
+
const { action, ...fields } = step;
|
|
38
|
+
if (!BATCH_ACTIONS.includes(action)) {
|
|
39
|
+
return `${label} has unknown action ${JSON.stringify(action)}. Use one of: ${BATCH_ACTIONS.join(', ')}.`;
|
|
40
|
+
}
|
|
41
|
+
if (action === 'wait') {
|
|
42
|
+
const keys = Object.keys(fields);
|
|
43
|
+
const validSelector = typeof fields.selector === 'string' && fields.selector.length > 0;
|
|
44
|
+
const validMs = Number.isInteger(fields.ms) && fields.ms >= 0 && fields.ms <= MAX_BATCH_WAIT_MS;
|
|
45
|
+
if (keys.length !== 1 || !(validSelector || validMs)) {
|
|
46
|
+
return `${label} (wait) needs either selector or ms, with ms from 0 to ${MAX_BATCH_WAIT_MS}.`;
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const required = REQUIRED_FIELDS[action];
|
|
51
|
+
for (const field of required) {
|
|
52
|
+
if (typeof fields[field] !== 'string') return `${label} (${action}) needs a string ${field}.`;
|
|
53
|
+
}
|
|
54
|
+
if (action === 'navigate' && !isValidUrl(fields.url)) return `${label} (navigate) needs a valid absolute URL.`;
|
|
55
|
+
const extra = Object.keys(fields).find((field) => !required.includes(field));
|
|
56
|
+
if (extra) return `${label} (${action}) has unknown field ${JSON.stringify(extra)}.`;
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function validateBatchSteps(input) {
|
|
61
|
+
if (!Array.isArray(input) || input.length === 0) {
|
|
62
|
+
return { ok: false, error: 'Batch steps must be a non-empty array.' };
|
|
63
|
+
}
|
|
64
|
+
if (input.length > MAX_BATCH_STEPS) {
|
|
65
|
+
return { ok: false, error: `A batch can have at most ${MAX_BATCH_STEPS} steps; this one has ${input.length}.` };
|
|
66
|
+
}
|
|
67
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
68
|
+
const error = validateStep(input[index], index);
|
|
69
|
+
if (error) return { ok: false, error };
|
|
70
|
+
}
|
|
71
|
+
return { ok: true, steps: input };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function boundedResult(value) {
|
|
75
|
+
if (value === undefined) return {};
|
|
76
|
+
const text = JSON.stringify(value);
|
|
77
|
+
if (text === undefined) return {};
|
|
78
|
+
if (text.length <= MAX_RESULT_CHARS) return { result: value };
|
|
79
|
+
return { result: text.slice(0, MAX_RESULT_CHARS), truncated: true };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Only evaluate results and fill match details go back, to keep the batch response small. */
|
|
83
|
+
function summarize(step, outcome) {
|
|
84
|
+
const data = outcome && typeof outcome === 'object' ? outcome : {};
|
|
85
|
+
if (step.action === 'evaluate') return boundedResult(data.result ?? data.data ?? data.value);
|
|
86
|
+
const details = data.data && typeof data.data === 'object' ? data.data : data;
|
|
87
|
+
const summary = {};
|
|
88
|
+
if (typeof details.changed === 'boolean') summary.changed = details.changed;
|
|
89
|
+
if (typeof details.matchCount === 'number') summary.matchCount = details.matchCount;
|
|
90
|
+
if (typeof details.matchIndex === 'number') summary.matchIndex = details.matchIndex;
|
|
91
|
+
return summary;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function errorText(error) {
|
|
95
|
+
if (error instanceof Error) return error.message;
|
|
96
|
+
return typeof error === 'string' ? error : 'Step failed';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A client error could quote what was typed, and batch results must not. */
|
|
100
|
+
function scrubTyped(message, step) {
|
|
101
|
+
const typed = step.value ?? step.text;
|
|
102
|
+
return typeof typed === 'string' && typed ? message.split(typed).join('[typed value]') : message;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Keep what tells an agent that a person has to step in, so it does not just retry. */
|
|
106
|
+
function handoffDetails(outcome) {
|
|
107
|
+
const data = outcome.data && typeof outcome.data === 'object' ? outcome.data : {};
|
|
108
|
+
return {
|
|
109
|
+
...(data.blocked === true ? { blocked: true } : {}),
|
|
110
|
+
...(typeof data.handoffRequired === 'boolean' ? { handoffRequired: data.handoffRequired } : {}),
|
|
111
|
+
...(typeof data.category === 'string' ? { category: data.category } : {}),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A blocked action may explain itself in data rather than error. */
|
|
116
|
+
function failureText(outcome) {
|
|
117
|
+
if (typeof outcome.error === 'string') return outcome.error;
|
|
118
|
+
const data = outcome.data && typeof outcome.data === 'object' ? outcome.data : {};
|
|
119
|
+
const reason = [data.message, data.reason, data.blockedBy, data.outcome, data.code].find((value) => typeof value === 'string' && value);
|
|
120
|
+
if (reason) return reason;
|
|
121
|
+
return 'Step failed with no reason given';
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* @param {Array<Record<string, unknown>>} steps Steps accepted by validateBatchSteps.
|
|
126
|
+
* @param {(step: Record<string, unknown>) => Promise<unknown>} execute
|
|
127
|
+
* @param {{ maxDurationMs?: number, now?: () => number }} [options] The limit is checked between steps.
|
|
128
|
+
*/
|
|
129
|
+
export async function runBatchSteps(steps, execute, { maxDurationMs = MAX_BATCH_DURATION_MS, now = Date.now } = {}) {
|
|
130
|
+
const results = [];
|
|
131
|
+
const deadline = now() + maxDurationMs;
|
|
132
|
+
for (let index = 0; index < steps.length; index += 1) {
|
|
133
|
+
const step = steps[index];
|
|
134
|
+
if (now() >= deadline) {
|
|
135
|
+
results.push({ step: index + 1, action: step.action, success: false, error: `Batch stopped: it reached the ${Math.round(maxDurationMs / 1000)} second limit before this step.` });
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
const outcome = await execute(step);
|
|
140
|
+
if (outcome && typeof outcome === 'object' && outcome.success === false) {
|
|
141
|
+
results.push({ step: index + 1, action: step.action, success: false, error: scrubTyped(failureText(outcome), step), ...handoffDetails(outcome) });
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
const summary = summarize(step, outcome);
|
|
145
|
+
// A broad selector may have filled the wrong field, so stop before anything can submit it.
|
|
146
|
+
if ((step.action === 'fill' || step.action === 'type') && summary.matchCount > 1) {
|
|
147
|
+
results.push({
|
|
148
|
+
step: index + 1,
|
|
149
|
+
action: step.action,
|
|
150
|
+
success: false,
|
|
151
|
+
applied: true,
|
|
152
|
+
...summary,
|
|
153
|
+
error: `The selector matched ${summary.matchCount} elements, and the value went into match ${summary.matchIndex + 1}. Stopped so nothing is submitted. Check the page, then use a more specific selector.`,
|
|
154
|
+
});
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
results.push({ step: index + 1, action: step.action, success: true, ...summary });
|
|
158
|
+
} catch (error) {
|
|
159
|
+
results.push({ step: index + 1, action: step.action, success: false, error: scrubTyped(errorText(error), step) });
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const failed = results.find((result) => !result.success);
|
|
164
|
+
return {
|
|
165
|
+
success: !failed,
|
|
166
|
+
total: steps.length,
|
|
167
|
+
completed: results.filter((result) => result.success).length,
|
|
168
|
+
...(failed ? { failedStep: failed.step, notRun: steps.length - results.length } : {}),
|
|
169
|
+
steps: results,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { MAX_BATCH_STEPS, runBatchSteps, validateBatchSteps } from './batch-steps.js';
|
|
3
|
+
|
|
4
|
+
describe('validateBatchSteps', () => {
|
|
5
|
+
test('accepts every action', () => {
|
|
6
|
+
const steps = [
|
|
7
|
+
{ action: 'navigate', url: 'https://example.com' }, { action: 'click', selector: 'a' }, { action: 'fill', selector: 'i', value: '' },
|
|
8
|
+
{ action: 'type', selector: 'i', text: 'x' }, { action: 'press', key: 'Enter' }, { action: 'select', selector: 's', value: 'v' },
|
|
9
|
+
{ action: 'hover', selector: 'a' }, { action: 'wait', selector: 'a' }, { action: 'wait', ms: 10 }, { action: 'wait_for_text', text: 'x' },
|
|
10
|
+
{ action: 'evaluate', script: '1+1' },
|
|
11
|
+
];
|
|
12
|
+
expect(validateBatchSteps(steps)).toEqual({ ok: true, steps });
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test.each([
|
|
16
|
+
[[], 'non-empty'],
|
|
17
|
+
['x', 'non-empty'],
|
|
18
|
+
[[null], 'Step 1 must be an object'],
|
|
19
|
+
[[{ action: 'delete_everything' }], 'unknown action'],
|
|
20
|
+
[[{ action: 'constructor' }], 'unknown action'],
|
|
21
|
+
[[{ action: 'click' }], 'needs a string selector'],
|
|
22
|
+
[[{ action: 'fill', selector: 'a' }], 'needs a string value'],
|
|
23
|
+
[[{ action: 'click', selector: 'a', force: true }], 'unknown field'],
|
|
24
|
+
[[{ action: 'wait' }], 'selector or ms'],
|
|
25
|
+
[[{ action: 'wait', ms: 30_001 }], 'selector or ms'],
|
|
26
|
+
[[{ action: 'wait', selector: 'a', ms: 1 }], 'selector or ms'],
|
|
27
|
+
[[{ action: 'navigate', url: 'not a url' }], 'valid absolute URL'],
|
|
28
|
+
])('rejects %j', (input, message) => {
|
|
29
|
+
const result = validateBatchSteps(input);
|
|
30
|
+
expect(result.ok).toBe(false);
|
|
31
|
+
expect(result.error).toContain(message);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('names the bad step and enforces the limit', () => {
|
|
35
|
+
expect(validateBatchSteps(Array.from({ length: MAX_BATCH_STEPS }, () => ({ action: 'press', key: 'a' }))).ok).toBe(true);
|
|
36
|
+
expect(validateBatchSteps([{ action: 'press', key: 'a' }, { action: 'nope' }]).error).toContain('Step 2');
|
|
37
|
+
const tooMany = Array.from({ length: MAX_BATCH_STEPS + 1 }, () => ({ action: 'press', key: 'a' }));
|
|
38
|
+
expect(validateBatchSteps(tooMany).error).toContain('at most 50');
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe('runBatchSteps', () => {
|
|
43
|
+
test('runs steps in order and reports success', async () => {
|
|
44
|
+
const seen = [];
|
|
45
|
+
const result = await runBatchSteps([{ action: 'click', selector: 'a' }, { action: 'press', key: 'Enter' }], async (step) => { seen.push(step.action); return { success: true }; });
|
|
46
|
+
expect(seen).toEqual(['click', 'press']);
|
|
47
|
+
expect(result).toEqual({ success: true, total: 2, completed: 2, steps: [
|
|
48
|
+
{ step: 1, action: 'click', success: true }, { step: 2, action: 'press', success: true },
|
|
49
|
+
] });
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test('stops after a thrown error, so a failed fill never reaches the submit', async () => {
|
|
53
|
+
const seen = [];
|
|
54
|
+
const result = await runBatchSteps(
|
|
55
|
+
[{ action: 'fill', selector: 'i', value: 'secret' }, { action: 'click', selector: 'submit' }, { action: 'press', key: 'Enter' }],
|
|
56
|
+
async (step) => { seen.push(step.action); throw new Error('Target is not editable: hidden input'); },
|
|
57
|
+
);
|
|
58
|
+
expect(seen).toEqual(['fill']);
|
|
59
|
+
expect(result).toMatchObject({ success: false, total: 3, completed: 0, failedStep: 1, notRun: 2 });
|
|
60
|
+
expect(result.steps[0].error).toContain('not editable');
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('stops after a success: false result', async () => {
|
|
64
|
+
const result = await runBatchSteps([{ action: 'click', selector: 'a' }, { action: 'click', selector: 'b' }], async () => ({ success: false, error: 'blocked' }));
|
|
65
|
+
expect(result).toMatchObject({ success: false, completed: 0, failedStep: 1, notRun: 1 });
|
|
66
|
+
expect(result.steps[0].error).toBe('blocked');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('uses the reason from a blocked result', async () => {
|
|
70
|
+
const blocked = await runBatchSteps([{ action: 'click', selector: 'a' }], async () => ({ success: false, data: { outcome: 'blocked', reason: 'cookie banner' } }));
|
|
71
|
+
expect(blocked.steps[0].error).toBe('cookie banner');
|
|
72
|
+
const silent = await runBatchSteps([{ action: 'click', selector: 'a' }], async () => ({ success: false }));
|
|
73
|
+
expect(silent.steps[0].error).toBe('Step failed with no reason given');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('keeps handoff details so an agent can stop for a person', async () => {
|
|
77
|
+
const result = await runBatchSteps([{ action: 'click', selector: 'a' }, { action: 'click', selector: 'b' }], async () => ({ success: false, data: { blocked: true, handoffRequired: true, category: 'login', message: 'Sign in required', password: 'x' } }));
|
|
78
|
+
expect(result.steps).toEqual([{ step: 1, action: 'click', success: false, error: 'Sign in required', blocked: true, handoffRequired: true, category: 'login' }]);
|
|
79
|
+
expect(result.notRun).toBe(1);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('scrubs typed values from error messages', async () => {
|
|
83
|
+
const thrown = await runBatchSteps([{ action: 'fill', selector: 'i', value: 'hunter2' }], async () => { throw new Error('could not set hunter2 on i'); });
|
|
84
|
+
expect(thrown.steps[0].error).toBe('could not set [typed value] on i');
|
|
85
|
+
const returned = await runBatchSteps([{ action: 'type', selector: 'i', text: 'hunter2' }], async () => ({ success: false, error: 'bad hunter2' }));
|
|
86
|
+
expect(returned.steps[0].error).toBe('bad [typed value]');
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('stops at the time limit, between steps', async () => {
|
|
90
|
+
let time = 0;
|
|
91
|
+
const seen = [];
|
|
92
|
+
const result = await runBatchSteps(
|
|
93
|
+
[{ action: 'press', key: 'a' }, { action: 'press', key: 'b' }, { action: 'press', key: 'c' }],
|
|
94
|
+
async (step) => { seen.push(step.key); time += 600; return { success: true }; },
|
|
95
|
+
{ maxDurationMs: 1000, now: () => time },
|
|
96
|
+
);
|
|
97
|
+
expect(seen).toEqual(['a', 'b']);
|
|
98
|
+
expect(result).toMatchObject({ success: false, completed: 2, failedStep: 3, notRun: 0 });
|
|
99
|
+
expect(result.steps[2].error).toContain('1 second limit');
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('never echoes typed values', async () => {
|
|
103
|
+
const result = await runBatchSteps([{ action: 'fill', selector: 'i', value: 'hunter2' }, { action: 'type', selector: 'i', text: 'hunter3' }], async () => ({ success: true, data: { changed: true, value: 'hunter2' } }));
|
|
104
|
+
expect(JSON.stringify(result)).not.toContain('hunter');
|
|
105
|
+
expect(result.steps[0]).toEqual({ step: 1, action: 'fill', success: true, changed: true });
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('a fill that matched several elements stops before the submit, and says it applied', async () => {
|
|
109
|
+
const seen = [];
|
|
110
|
+
const result = await runBatchSteps(
|
|
111
|
+
[{ action: 'fill', selector: 'form input', value: '2' }, { action: 'click', selector: 'button' }],
|
|
112
|
+
async (step) => { seen.push(step.action); return { success: true, data: { changed: true, matchCount: 2, matchIndex: 1 } }; },
|
|
113
|
+
);
|
|
114
|
+
expect(seen).toEqual(['fill']);
|
|
115
|
+
expect(result).toMatchObject({ success: false, completed: 0, failedStep: 1, notRun: 1 });
|
|
116
|
+
expect(result.steps[0]).toMatchObject({ applied: true, matchCount: 2, matchIndex: 1 });
|
|
117
|
+
expect(result.steps[0].error).toContain('match 2');
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test('returns evaluate results and bounds large ones', async () => {
|
|
121
|
+
const small = await runBatchSteps([{ action: 'evaluate', script: '1' }], async () => ({ success: true, result: { total: '$10' } }));
|
|
122
|
+
expect(small.steps[0].result).toEqual({ total: '$10' });
|
|
123
|
+
const large = await runBatchSteps([{ action: 'evaluate', script: '1' }], async () => ({ success: true, data: 'x'.repeat(9000) }));
|
|
124
|
+
expect(large.steps[0].truncated).toBe(true);
|
|
125
|
+
expect(String(large.steps[0].result).length).toBe(4000);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const ISSUE_REPORT_VERSION: 1;
|
|
2
|
+
export const REPORT_BODY_LIMIT: number;
|
|
3
|
+
export interface ReportSelection { feedbackIds: string[]; observationIds: string[]; suggestionIds: string[] }
|
|
4
|
+
export interface IssueReport { version: 1; source: { sourceType: string; sourceId?: string; shareToken?: string; schemaVersion: string; shareUrl: string }; selection: ReportSelection; title: string; body: string }
|
|
5
|
+
export type IssueReportScope = { kind: 'combined' } | { kind: 'issue'; issueId: string };
|
|
6
|
+
export interface IdentifiedReportIssue { id: string; title: string; description: string; timestampMs?: number; selection: ReportSelection; evidenceRefs: Array<{ type?: string; index?: number; timestampMs?: number; startMs?: number; endMs?: number; [key: string]: unknown }>; expectedBehavior: string }
|
|
7
|
+
export function getIssueReportScopes(bundle: unknown): IdentifiedReportIssue[];
|
|
8
|
+
export function durableShareUrl(value: string): string;
|
|
9
|
+
export function buildIssueReport(bundle: unknown, options?: { sourceUrl?: string; scope?: IssueReportScope; selection?: Partial<ReportSelection> }): IssueReport;
|
|
10
|
+
export function serializeIssueReport(report: Pick<IssueReport, 'title' | 'body'>): string;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/** Recipient-visible canonical share -> reviewed issue draft. No owner bundles. */
|
|
2
|
+
export const ISSUE_REPORT_VERSION = 1;
|
|
3
|
+
export const REPORT_BODY_LIMIT = 60000;
|
|
4
|
+
export function durableShareUrl(value) {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (url.toString().length > 2048 || !['https:', 'http:'].includes(url.protocol) || url.username || url.password || !/^\/s\/[^/]+$/.test(url.pathname)) throw new Error('A durable share page URL is required');
|
|
7
|
+
url.search = ''; url.hash = '';
|
|
8
|
+
return url.toString();
|
|
9
|
+
}
|
|
10
|
+
// Narrative fields may themselves contain temporary asset URLs. Never export those.
|
|
11
|
+
function text(value, max = 4000) {
|
|
12
|
+
return String(value ?? '').replace(/https?:\/\/[^\s<>]+/gi, raw => {
|
|
13
|
+
try { const u = new URL(raw); if ([...u.searchParams.keys()].some(k => /^(vt|token|signature|expires|x-amz-.+|x-goog-.+)$/i.test(k))) return '[temporary link omitted]'; } catch {}
|
|
14
|
+
return raw;
|
|
15
|
+
}).replace(/<[^>]*>/g, '').slice(0, max).trim();
|
|
16
|
+
}
|
|
17
|
+
const CLAIM_SECTIONS = [['feedbackIds', 'userReportedFeedback', 'User feedback'], ['observationIds', 'directObservations', 'Observations'], ['suggestionIds', 'suggestedChanges', 'Suggestions']];
|
|
18
|
+
const claims = (bundle, field) => (Array.isArray(bundle?.[field]) ? bundle[field] : []).filter(e => e && typeof e.id === 'string' && typeof e.text === 'string');
|
|
19
|
+
const refs = entry => (Array.isArray(entry?.evidenceRefs) ? entry.evidenceRefs : []).filter(r => r && typeof r === 'object');
|
|
20
|
+
const normalized = value => typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
21
|
+
// A screenshot may illustrate several distinct issues. Only an exact claim or
|
|
22
|
+
// timestamp links observations; sharing an image alone does not establish relevance.
|
|
23
|
+
function related(entry, issue, description) {
|
|
24
|
+
return normalized(entry.text) === normalized(description)
|
|
25
|
+
|| (Number.isFinite(issue.timestampMs) && entry.timestampMs === issue.timestampMs);
|
|
26
|
+
}
|
|
27
|
+
function stableId(value) {
|
|
28
|
+
let hash = 2166136261;
|
|
29
|
+
for (const char of value) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619);
|
|
30
|
+
return (hash >>> 0).toString(36);
|
|
31
|
+
}
|
|
32
|
+
/** Identified issues from recipient-visible analysis, with canonical claim links. */
|
|
33
|
+
export function getIssueReportScopes(bundle) {
|
|
34
|
+
const issues = (Array.isArray(bundle?.analysis?.issues) ? bundle.analysis.issues : [])
|
|
35
|
+
.filter(issue => issue && typeof issue.description === 'string' && text(issue.description));
|
|
36
|
+
// Older shares can carry identified issues only as suggested changes with a
|
|
37
|
+
// rationale. Insights alone are not treated as identified defects.
|
|
38
|
+
const sources = issues.length ? issues : claims(bundle, 'suggestedChanges')
|
|
39
|
+
.filter(entry => typeof entry.rationale === 'string' && text(entry.rationale))
|
|
40
|
+
.map(entry => ({ ...entry, description: entry.rationale, suggestedFix: entry.text }));
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
return sources.flatMap(issue => {
|
|
43
|
+
const title = text(issue.description, 200).replace(/\s+/g, ' ');
|
|
44
|
+
const id = typeof issue.id === 'string' && issue.id ? `issue:${issue.id}`
|
|
45
|
+
: `issue:${stableId(JSON.stringify([issue.description, issue.timestampMs ?? null, issue.suggestedFix ?? null]))}`;
|
|
46
|
+
if (seen.has(id)) return [];
|
|
47
|
+
seen.add(id);
|
|
48
|
+
const selection = {};
|
|
49
|
+
const evidenceRefs = [...refs(issue)];
|
|
50
|
+
for (const [key, field] of CLAIM_SECTIONS) {
|
|
51
|
+
const entries = claims(bundle, field).filter(entry => field === 'suggestedChanges'
|
|
52
|
+
? normalized(entry.rationale) === normalized(issue.description)
|
|
53
|
+
|| normalized(entry.text) === normalized(issue.description)
|
|
54
|
+
|| (normalized(issue.suggestedFix) && normalized(entry.text) === normalized(issue.suggestedFix)
|
|
55
|
+
&& (!Number.isFinite(issue.timestampMs) || entry.timestampMs === issue.timestampMs))
|
|
56
|
+
: related(entry, issue, issue.description));
|
|
57
|
+
selection[key] = entries.map(entry => entry.id);
|
|
58
|
+
evidenceRefs.push(...entries.flatMap(refs));
|
|
59
|
+
}
|
|
60
|
+
return [{ id, title, description: text(issue.description), timestampMs: issue.timestampMs, selection, evidenceRefs,
|
|
61
|
+
expectedBehavior: typeof issue.expectedBehavior === 'string' ? text(issue.expectedBehavior) : '' }];
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function expectedBehavior(bundle, issue, options) {
|
|
65
|
+
if (issue?.expectedBehavior) return `From source analysis (confirm with the reporter):\n${issue.expectedBehavior}`;
|
|
66
|
+
const feedback = claims(bundle, 'userReportedFeedback').filter(entry =>
|
|
67
|
+
(!issue || issue.selection.feedbackIds.includes(entry.id))
|
|
68
|
+
&& (!options.selection?.feedbackIds || options.selection.feedbackIds.includes(entry.id)));
|
|
69
|
+
const moments = (Array.isArray(bundle.analysis.moments) ? bundle.analysis.moments : []).filter(entry =>
|
|
70
|
+
entry?.kind === 'narration' && (!issue || (Number.isFinite(issue.timestampMs) && entry.timestampMs === issue.timestampMs)));
|
|
71
|
+
// Preserve the source's wording and provenance. Requests are not acceptance
|
|
72
|
+
// criteria, and suggested fixes must never become confirmed expectations.
|
|
73
|
+
const requests = [...feedback.map(entry => entry.text), ...moments.map(entry => entry.description)]
|
|
74
|
+
.filter(value => typeof value === 'string' && /\b(wants?|should|would like|desire|requests?)\b/i.test(value))
|
|
75
|
+
.map(value => text(value, 600));
|
|
76
|
+
const unique = [...new Set(requests)].slice(0, 5);
|
|
77
|
+
return unique.length
|
|
78
|
+
? `Reporter requests (from source analysis; confirm wording):\n${unique.map(value => `- ${value}`).join('\n')}`
|
|
79
|
+
: 'Needs reporter input. Edit this section to describe the intended behavior.';
|
|
80
|
+
}
|
|
81
|
+
export function buildIssueReport(bundle, options = {}) {
|
|
82
|
+
if (!bundle || !['thinkrun.share', 'thinkbrowse.share'].includes(bundle.artifactType) || !bundle.context || !bundle.analysis || !bundle.evidence) throw new Error('Expected a canonical recipient share');
|
|
83
|
+
const shareUrl = durableShareUrl(options.sourceUrl || bundle.context.shareUrl);
|
|
84
|
+
if (options.scope && !['combined', 'issue'].includes(options.scope.kind)) throw new Error('Invalid report scope');
|
|
85
|
+
const issue = options.scope?.kind === 'issue' ? getIssueReportScopes(bundle).find(entry => entry.id === options.scope.issueId) : null;
|
|
86
|
+
if (options.scope?.kind === 'issue' && !issue) throw new Error('The selected issue is no longer available');
|
|
87
|
+
const selection = {};
|
|
88
|
+
const sections = CLAIM_SECTIONS;
|
|
89
|
+
const parts = ['## Summary', issue?.description || text(bundle.summary || bundle.analysis.summary) || 'No summary available.', '## Expected behavior', expectedBehavior(bundle, issue, options)];
|
|
90
|
+
const footer = ['## Context and limitations', bundle.analysis.status === 'complete' ? 'Analysis available; verify observations against the source.' : 'Analysis incomplete; additional context may be needed.', 'Raw transcript, console logs and network requests are omitted.', '## Source', `[View ${bundle.context.sourceType === 'recording' ? 'recording' : 'session'}](${shareUrl})`];
|
|
91
|
+
// Reserve the footer and all headings before allocating an equal budget to each
|
|
92
|
+
// claim category. Add only whole entries, so selection describes exported claims.
|
|
93
|
+
const reserved = [...parts, ...sections.map(([, , heading]) => `## ${heading}`), ...footer].join('\n\n').length + 512;
|
|
94
|
+
const sectionBudget = Math.floor((REPORT_BODY_LIMIT - reserved) / sections.length);
|
|
95
|
+
for (const [key, field, heading] of sections) {
|
|
96
|
+
const requested = options.selection?.[key];
|
|
97
|
+
const entries = (Array.isArray(bundle[field]) ? bundle[field] : []).filter(e => e && typeof e.id === 'string' && typeof e.text === 'string' && (!requested || requested.includes(e.id)) && (!issue || issue.selection[key].includes(e.id)));
|
|
98
|
+
selection[key] = [];
|
|
99
|
+
const lines = [];
|
|
100
|
+
let used = 0;
|
|
101
|
+
for (const e of entries.slice(0, 40)) {
|
|
102
|
+
const refs = (Array.isArray(e.evidenceRefs) ? e.evidenceRefs : []).filter(r => r && typeof r === 'object').slice(0, 8).map(r => {
|
|
103
|
+
const timestamp = r.timestampMs ?? r.startMs;
|
|
104
|
+
return `${text(r.type, 30)}${Number.isFinite(r.index) ? ` ${r.index + 1}` : ''}${Number.isFinite(timestamp) ? ` at ${(timestamp / 1000).toFixed(1)}s` : ''}`;
|
|
105
|
+
});
|
|
106
|
+
const line = `- ${text(e.text, 800)}${refs.length ? ` ([evidence: ${refs.join(', ')}](${shareUrl}))` : ''}`;
|
|
107
|
+
if (used + line.length + 1 > sectionBudget) break;
|
|
108
|
+
lines.push(line); used += line.length + 1; selection[key].push(e.id);
|
|
109
|
+
}
|
|
110
|
+
const omitted = entries.length - lines.length;
|
|
111
|
+
parts.push(`## ${heading}`, ...(field === 'suggestedChanges' && lines.length ? ['Suggested changes from analysis; not confirmed expected behavior.'] : []), lines.length ? lines.join('\n') : 'None supplied.');
|
|
112
|
+
if (omitted) parts.push(`${omitted} additional claims omitted to keep this report concise.`);
|
|
113
|
+
}
|
|
114
|
+
parts.push(...footer);
|
|
115
|
+
const firstClaim = sections.flatMap(([key, field]) => claims(bundle, field).filter(entry => selection[key].includes(entry.id)))[0];
|
|
116
|
+
const combinedTitle = getIssueReportScopes(bundle).length > 1
|
|
117
|
+
? `Combined feedback: ${bundle.summary || bundle.analysis.summary || getIssueReportScopes(bundle).map(entry => entry.title).join('; ')}` : '';
|
|
118
|
+
const title = issue?.title || text(combinedTitle || firstClaim?.text || bundle.summary || bundle.analysis.summary || bundle.context.title, 200).replace(/\s+/g, ' ') || 'Issue report';
|
|
119
|
+
return { version: ISSUE_REPORT_VERSION, source: { sourceType: bundle.context.sourceType, sourceId: bundle.context.identifiers?.sourceId, shareToken: bundle.context.identifiers?.shareToken, schemaVersion: bundle.schemaVersion, shareUrl }, selection, title, body: parts.join('\n\n') };
|
|
120
|
+
}
|
|
121
|
+
export function serializeIssueReport(report) {
|
|
122
|
+
if (typeof report.title !== 'string' || !report.title.trim() || report.title.length > 200 || typeof report.body !== 'string' || report.body.length > REPORT_BODY_LIMIT) throw new Error('Invalid report title or body');
|
|
123
|
+
// Exact reviewed body is retained. Reject ephemeral links introduced by edits.
|
|
124
|
+
if (/[?&](?:vt|token|signature|expires|x-amz-[^=\s]+|x-goog-[^=\s]+)=/i.test(`${report.title}\n${report.body}`)) throw new Error('Replace temporary asset URLs with a durable share link');
|
|
125
|
+
return `# ${report.title}\n\n${report.body}\n`;
|
|
126
|
+
}
|