@thinkrun/mcp 0.3.13 → 0.3.16
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/CHANGELOG.md +26 -0
- package/README.md +39 -2
- package/dist/bin/thinkrun-mcp.js +55 -11
- package/dist/bin/thinkrun-mcp.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/group-binding-key.d.ts +5 -0
- package/dist/shared/group-binding-key.js +15 -0
- package/dist/shared/group-binding-key.test.js +50 -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/native-type-budget.d.ts +16 -0
- package/dist/shared/native-type-budget.js +28 -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-drips.d.ts +13 -0
- package/dist/shared/onboarding-drips.js +100 -0
- package/dist/shared/onboarding-metrics.d.ts +4 -0
- package/dist/shared/onboarding-metrics.js +53 -0
- package/dist/shared/onboarding-public-consent.cjs +3 -0
- package/dist/shared/onboarding-public-consent.d.ts +1 -0
- package/dist/shared/onboarding-public-consent.js +3 -0
- package/dist/shared/onboarding-public-consent.json +3 -0
- package/dist/shared/recording-upload.d.ts +5 -0
- package/dist/shared/recording-upload.js +184 -0
- package/dist/shared/recording-upload.test.js +157 -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/account-connection.d.ts +7 -0
- package/dist/src/account-connection.d.ts.map +1 -0
- package/dist/src/account-connection.js +37 -0
- package/dist/src/account-connection.js.map +1 -0
- package/dist/src/client.d.ts +14 -0
- package/dist/src/client.d.ts.map +1 -1
- package/dist/src/cloud-client.d.ts +2 -0
- package/dist/src/cloud-client.d.ts.map +1 -1
- package/dist/src/cloud-client.js +8 -0
- package/dist/src/cloud-client.js.map +1 -1
- package/dist/src/local-client.d.ts +23 -4
- package/dist/src/local-client.d.ts.map +1 -1
- package/dist/src/local-client.js +148 -49
- package/dist/src/local-client.js.map +1 -1
- package/dist/src/local-saving.d.ts +51 -0
- package/dist/src/local-saving.d.ts.map +1 -0
- package/dist/src/local-saving.js +150 -0
- package/dist/src/local-saving.js.map +1 -0
- package/dist/src/onboarding.d.ts +1 -1
- package/dist/src/onboarding.js +1 -1
- package/dist/src/recordings.d.ts +29 -0
- package/dist/src/recordings.d.ts.map +1 -0
- package/dist/src/recordings.js +68 -0
- package/dist/src/recordings.js.map +1 -0
- package/dist/src/server.d.ts +30 -1
- package/dist/src/server.d.ts.map +1 -1
- package/dist/src/server.js +211 -43
- package/dist/src/server.js.map +1 -1
- package/package.json +8 -6
|
@@ -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,5 @@
|
|
|
1
|
+
/** Return a collision-resistant filesystem key for a caller-provided group name. */
|
|
2
|
+
export declare function getGroupBindingKey(group: string): string;
|
|
3
|
+
|
|
4
|
+
/** Return the historical key for read-only legacy lookup and safe cleanup. */
|
|
5
|
+
export declare function getLegacyGroupBindingKey(group: string): string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const GROUP_KEY_STEM_LIMIT = 64;
|
|
4
|
+
|
|
5
|
+
/** Return a collision-resistant filesystem key for a caller-provided group name. */
|
|
6
|
+
export function getGroupBindingKey(group) {
|
|
7
|
+
const stem = group.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, GROUP_KEY_STEM_LIMIT);
|
|
8
|
+
const digest = createHash('sha256').update(Buffer.from(group, 'utf16le')).digest('hex');
|
|
9
|
+
return `${stem}~${digest}`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Return the historical key for read-only legacy lookup and safe cleanup. */
|
|
13
|
+
export function getLegacyGroupBindingKey(group) {
|
|
14
|
+
return group.replace(/[^A-Za-z0-9_-]/g, '_') || 'default';
|
|
15
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { getGroupBindingKey, getLegacyGroupBindingKey } from './group-binding-key.js';
|
|
4
|
+
|
|
5
|
+
describe('group binding keys', () => {
|
|
6
|
+
test('puts every name in a bounded hashed namespace', () => {
|
|
7
|
+
for (const group of ['agent_42-team', 'a'.repeat(240), 'a'.repeat(241)]) {
|
|
8
|
+
const key = getGroupBindingKey(group);
|
|
9
|
+
expect(key).not.toBe(group);
|
|
10
|
+
expect(key).toMatch(/^[A-Za-z0-9_-]*~[a-f0-9]{64}$/);
|
|
11
|
+
expect(key.length).toBeLessThanOrEqual(129);
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test('case-folding variants get distinct keys on case-insensitive filesystems', () => {
|
|
16
|
+
const keys = ['Team', 'team', 'TEAM'].map(getGroupBindingKey);
|
|
17
|
+
expect(new Set(keys).size).toBe(3);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('Windows device basenames are hashed into valid non-device filenames', () => {
|
|
21
|
+
for (const group of ['con', 'prn', 'aux', 'nul', 'com1', 'com9', 'lpt1', 'lpt9']) {
|
|
22
|
+
const key = getGroupBindingKey(group);
|
|
23
|
+
expect(key).not.toBe(group);
|
|
24
|
+
expect(key).toMatch(/^[a-z0-9_-]*~[a-f0-9]{64}$/);
|
|
25
|
+
expect(key).not.toMatch(/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('separates names that collided under the historical sanitizer', () => {
|
|
30
|
+
expect(getLegacyGroupBindingKey('a b')).toBe(getLegacyGroupBindingKey('a_b'));
|
|
31
|
+
expect(getGroupBindingKey('a b')).not.toBe(getGroupBindingKey('a_b'));
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('hashes Unicode and lone surrogate code units distinctly within the path bound', () => {
|
|
35
|
+
for (const group of ['研究', '\uD800', '\uDC00', 'x'.repeat(400) + ' /unsafe']) {
|
|
36
|
+
const key = getGroupBindingKey(group);
|
|
37
|
+
const expectedHash = createHash('sha256').update(Buffer.from(group, 'utf16le')).digest('hex');
|
|
38
|
+
expect(key.endsWith(`~${expectedHash}`)).toBe(true);
|
|
39
|
+
expect(key.length).toBeLessThanOrEqual(129);
|
|
40
|
+
expect(key).toMatch(/^[A-Za-z0-9_-]*~[a-f0-9]{64}$/);
|
|
41
|
+
}
|
|
42
|
+
expect(getGroupBindingKey('\uD800')).not.toBe(getGroupBindingKey('\uDC00'));
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('empty input hashes independently of the legacy default alias', () => {
|
|
46
|
+
expect(getLegacyGroupBindingKey('')).toBe('default');
|
|
47
|
+
expect(getGroupBindingKey('')).not.toBe('default');
|
|
48
|
+
expect(getGroupBindingKey('')).toMatch(/^~[a-f0-9]{64}$/);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { test, expect } from 'bun:test';
|
|
2
|
+
import { buildIssueReport, serializeIssueReport, getIssueReportScopes } from './issue-report.js';
|
|
3
|
+
const bundle = { artifactType: 'thinkrun.share', schemaVersion: '2026-06-21', context: { title: 'Button fails', sourceType: 'recording', shareUrl: 'https://browse.is/s/abc?vt=private', identifiers: { shareToken: 'abc', sourceId: 'rec' } }, analysis: { status: 'incomplete' }, evidence: { transcript: 'PRIVATE transcript', consoleLogs: ['SECRET'], video: { url: 'https://signed.test/?X-Amz-Signature=secret' } }, userReportedFeedback: [{ id: 'f', text: 'Submit does nothing', evidenceRefs: [{ type: 'video_span', startMs: 1200 }] }], directObservations: [{ id: 'o', text: 'Button remains visible', evidenceRefs: [] }], suggestedChanges: [{ id: 's', text: 'Show progress', evidenceRefs: [] }] };
|
|
4
|
+
test('maps separate claims, unknown expectation, evidence and durable source only', () => {
|
|
5
|
+
const r = buildIssueReport(bundle); const md = serializeIssueReport(r);
|
|
6
|
+
expect(md).toContain('## User feedback'); expect(md).toContain('## Observations'); expect(md).toContain('## Suggestions');
|
|
7
|
+
expect(md).toContain('Needs reporter input'); expect(md).toContain('Analysis incomplete'); expect(md).toContain('video_span at 1.2s');
|
|
8
|
+
expect(md).not.toMatch(/PRIVATE|SECRET|signed.test|vt=/); expect(r.source.shareUrl).toBe('https://browse.is/s/abc');
|
|
9
|
+
});
|
|
10
|
+
test('selection omits unselected claims and preserves exact edited output', () => {
|
|
11
|
+
const r = buildIssueReport(bundle, { selection: { feedbackIds: [] } }); expect(r.body).not.toContain('Submit does nothing');
|
|
12
|
+
r.title = 'Edited'; r.body = 'Exact\n\n text'; expect(serializeIssueReport(r)).toBe('# Edited\n\nExact\n\n text\n');
|
|
13
|
+
});
|
|
14
|
+
test('rejects owner bundle and unsafe URLs; omits temporary links in narrative', () => {
|
|
15
|
+
expect(() => buildIssueReport({ recording: {} })).toThrow();
|
|
16
|
+
expect(() => buildIssueReport(bundle, { sourceUrl: 'javascript:bad' })).toThrow();
|
|
17
|
+
const r = buildIssueReport({ ...bundle, summary: 'See https://x.test/a?vt=secret' }); expect(r.body).not.toContain('vt=secret');
|
|
18
|
+
expect(() => serializeIssueReport({ title: 'X', body: 'https://x.test/a?vt=secret' })).toThrow();
|
|
19
|
+
});
|
|
20
|
+
test('budgets whole claims and preserves footer with exact included selection', () => {
|
|
21
|
+
const entries = Array.from({ length: 40 }, (_, i) => ({ id: `claim-${i}`, text: `Claim ${i}: ${'x'.repeat(790)}`, evidenceRefs: [{ type: 'video_span', startMs: i * 1000 }] }));
|
|
22
|
+
const r = buildIssueReport({ ...bundle, summary: 's'.repeat(4000), userReportedFeedback: entries, directObservations: entries, suggestedChanges: entries });
|
|
23
|
+
expect(r.body.length).toBeLessThanOrEqual(60000); expect(r.body).toContain('## Context and limitations'); expect(r.body).toEndWith('[View recording](https://browse.is/s/abc)');
|
|
24
|
+
for (const [key, heading] of [['feedbackIds', 'User feedback'], ['observationIds', 'Observations'], ['suggestionIds', 'Suggestions']] as const) {
|
|
25
|
+
const section = r.body.split(`## ${heading}\n\n`)[1].split('\n\n## ')[0];
|
|
26
|
+
expect(r.selection[key].length).toBeLessThan(40);
|
|
27
|
+
for (const entry of entries) expect(section.includes(`${entry.text.slice(0, 20)}`)).toBe(r.selection[key].includes(entry.id));
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
test('rejects temporary credential URLs in edited titles', () => {
|
|
31
|
+
for (const parameter of ['vt', 'token', 'X-Amz-Signature', 'X-Goog-Credential']) {
|
|
32
|
+
expect(() => serializeIssueReport({ title: `See https://asset.test/a?${parameter}=secret`, body: 'Reviewed body' })).toThrow('durable share link');
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const issueBundle = {
|
|
37
|
+
...bundle,
|
|
38
|
+
summary: 'Submit fails and the menu overlaps the footer.',
|
|
39
|
+
analysis: { status: 'complete', issues: [
|
|
40
|
+
{ description: 'Submit does nothing', suggestedFix: 'Show submit progress', timestampMs: 1200 },
|
|
41
|
+
{ description: 'Menu overlaps the footer', suggestedFix: 'Reposition menu', timestampMs: 8000 },
|
|
42
|
+
] },
|
|
43
|
+
userReportedFeedback: [
|
|
44
|
+
{ id: 'f-submit', text: 'I cannot submit this form', timestampMs: 1200, evidenceRefs: [{ type: 'screenshot', index: 0 }] },
|
|
45
|
+
{ id: 'f-menu', text: 'The menu covers the footer', timestampMs: 8000, evidenceRefs: [{ type: 'screenshot', index: 1 }] },
|
|
46
|
+
],
|
|
47
|
+
directObservations: [
|
|
48
|
+
{ id: 'o-submit', text: 'Button remains visible', timestampMs: 1200, evidenceRefs: [{ type: 'screenshot', index: 0 }] },
|
|
49
|
+
{ id: 'o-menu', text: 'Menu covers content', timestampMs: 8000, evidenceRefs: [{ type: 'screenshot', index: 1 }] },
|
|
50
|
+
{ id: 'o-unrelated', text: 'Another defect shares this screenshot', timestampMs: 2000, evidenceRefs: [{ type: 'screenshot', index: 0 }] },
|
|
51
|
+
],
|
|
52
|
+
suggestedChanges: [
|
|
53
|
+
{ id: 's-submit', text: 'Show submit progress', rationale: 'Submit does nothing', timestampMs: 1200, evidenceRefs: [{ type: 'screenshot', index: 0 }] },
|
|
54
|
+
{ id: 's-menu', text: 'Reposition menu', rationale: 'Menu overlaps the footer', timestampMs: 8000, evidenceRefs: [{ type: 'screenshot', index: 1 }] },
|
|
55
|
+
],
|
|
56
|
+
};
|
|
57
|
+
test('identified issue scopes are stable across source ordering and link canonical claims', () => {
|
|
58
|
+
const scopes = getIssueReportScopes(issueBundle);
|
|
59
|
+
const reordered = getIssueReportScopes({ ...issueBundle, analysis: { ...issueBundle.analysis, issues: [...issueBundle.analysis.issues].reverse() } });
|
|
60
|
+
expect(scopes).toHaveLength(2);
|
|
61
|
+
expect(scopes[0].id).toBe(reordered[1].id);
|
|
62
|
+
expect(scopes[0].selection).toEqual({ feedbackIds: ['f-submit'], observationIds: ['o-submit'], suggestionIds: ['s-submit'] });
|
|
63
|
+
expect(scopes[0].evidenceRefs.every(ref => ref.index === 0)).toBe(true);
|
|
64
|
+
});
|
|
65
|
+
test('one issue excludes other issues, global summary, unrelated observations and evidence', () => {
|
|
66
|
+
const scope = getIssueReportScopes(issueBundle)[0];
|
|
67
|
+
const report = buildIssueReport(issueBundle, { scope: { kind: 'issue', issueId: scope.id } });
|
|
68
|
+
expect(report.title).toBe('Submit does nothing');
|
|
69
|
+
expect(report.selection).toEqual(scope.selection);
|
|
70
|
+
expect(report.body).toContain('I cannot submit this form');
|
|
71
|
+
expect(report.body).toContain('Button remains visible');
|
|
72
|
+
expect(report.body).not.toMatch(/menu|footer|Another defect|screenshot 2/i);
|
|
73
|
+
expect(report.body).toContain('Needs reporter input.');
|
|
74
|
+
expect(report.body).not.toContain('## Steps');
|
|
75
|
+
const narrowed = buildIssueReport(issueBundle, { scope: { kind: 'issue', issueId: scope.id }, selection: { feedbackIds: ['f-menu'], suggestionIds: [] } });
|
|
76
|
+
expect(narrowed.selection.feedbackIds).toEqual([]);
|
|
77
|
+
expect(narrowed.selection.suggestionIds).toEqual([]);
|
|
78
|
+
});
|
|
79
|
+
test('combined remains default and titles describe included claims instead of recording name', () => {
|
|
80
|
+
expect(buildIssueReport(issueBundle)).toEqual(buildIssueReport(issueBundle, { scope: { kind: 'combined' } }));
|
|
81
|
+
expect(buildIssueReport(issueBundle).title).toBe('Combined feedback: Submit fails and the menu overlaps the footer.');
|
|
82
|
+
expect(buildIssueReport(issueBundle).body).toContain('Menu covers content');
|
|
83
|
+
expect(() => buildIssueReport(issueBundle, { scope: { kind: 'issue', issueId: 'missing' } })).toThrow('no longer available');
|
|
84
|
+
});
|
|
85
|
+
test('uses only explicit expected behavior, and supports legacy rationale without inventing issues', () => {
|
|
86
|
+
const expected = { ...issueBundle, analysis: { ...issueBundle.analysis, issues: [{ ...issueBundle.analysis.issues[0], expectedBehavior: 'The completed form should be submitted.' }] } };
|
|
87
|
+
const report = buildIssueReport(expected, { scope: { kind: 'issue', issueId: getIssueReportScopes(expected)[0].id } });
|
|
88
|
+
expect(report.body).toContain('The completed form should be submitted.');
|
|
89
|
+
expect(getIssueReportScopes({ ...issueBundle, analysis: {} })).toHaveLength(2);
|
|
90
|
+
expect(getIssueReportScopes(bundle)).toEqual([]);
|
|
91
|
+
expect(getIssueReportScopes(null)).toEqual([]);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test('attributes reporter requests without promoting model fixes to expected behavior', () => {
|
|
95
|
+
const source = { ...issueBundle,
|
|
96
|
+
userReportedFeedback: [{ ...issueBundle.userReportedFeedback[0], source: 'narration', text: 'User wants visible submission progress' }],
|
|
97
|
+
analysis: { ...issueBundle.analysis, moments: [
|
|
98
|
+
{ kind: 'narration', timestampMs: 1200, description: 'User says the page should show progress' },
|
|
99
|
+
{ kind: 'narration', timestampMs: 8000, description: 'User wants a smaller menu' },
|
|
100
|
+
{ kind: 'issue', timestampMs: 1200, description: 'The backend should use a queue' },
|
|
101
|
+
] },
|
|
102
|
+
};
|
|
103
|
+
const report = buildIssueReport(source, { scope: { kind: 'issue', issueId: getIssueReportScopes(source)[0].id } });
|
|
104
|
+
const expected = report.body.split('## Expected behavior')[1].split('## User feedback')[0];
|
|
105
|
+
expect(expected).toContain('Reporter requests (from source analysis; confirm wording)');
|
|
106
|
+
expect(expected).toContain('User wants visible submission progress');
|
|
107
|
+
expect(expected).toContain('User says the page should show progress');
|
|
108
|
+
expect(expected).not.toMatch(/smaller menu|backend|Show submit progress/);
|
|
109
|
+
expect(report.body).toContain('Suggested changes from analysis; not confirmed expected behavior.');
|
|
110
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const NATIVE_TYPE_EXECUTION_BUFFER_MS: 5000;
|
|
2
|
+
export declare const NATIVE_TYPE_MAX_TIMEOUT_MS: 600000;
|
|
3
|
+
|
|
4
|
+
export interface NativeTypeBudget {
|
|
5
|
+
characterCount: number;
|
|
6
|
+
delayMs: number;
|
|
7
|
+
requiredTimeoutMs: number;
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
exceedsLimit: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export declare function getNativeTypeBudget(
|
|
13
|
+
text: string,
|
|
14
|
+
delay: number | undefined,
|
|
15
|
+
defaultTimeoutMs: number,
|
|
16
|
+
): NativeTypeBudget;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const NATIVE_TYPE_EXECUTION_BUFFER_MS = 5_000;
|
|
2
|
+
export const NATIVE_TYPE_MAX_TIMEOUT_MS = 600_000;
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Compute the native host's typing command timeout without dispatching it.
|
|
6
|
+
* Character count follows Unicode code points, matching Array.from(text).
|
|
7
|
+
*/
|
|
8
|
+
export function getNativeTypeBudget(text, delay, defaultTimeoutMs) {
|
|
9
|
+
const characterCount = Array.from(text).length;
|
|
10
|
+
const normalizedDelayMs = typeof delay === 'number' && Number.isFinite(delay) && delay > 0
|
|
11
|
+
? delay
|
|
12
|
+
: 0;
|
|
13
|
+
const requiredTimeoutMs = Math.ceil(
|
|
14
|
+
characterCount * normalizedDelayMs + NATIVE_TYPE_EXECUTION_BUFFER_MS,
|
|
15
|
+
);
|
|
16
|
+
const timeoutMs = Math.min(
|
|
17
|
+
NATIVE_TYPE_MAX_TIMEOUT_MS,
|
|
18
|
+
Math.max(defaultTimeoutMs, requiredTimeoutMs),
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
characterCount,
|
|
23
|
+
delayMs: normalizedDelayMs,
|
|
24
|
+
requiredTimeoutMs,
|
|
25
|
+
timeoutMs,
|
|
26
|
+
exceedsLimit: requiredTimeoutMs > NATIVE_TYPE_MAX_TIMEOUT_MS,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A wait straight after a click can reach the old page as Chrome moves it into the back/forward
|
|
3
|
+
* cache, which closes the message channel. Only use this for reads with no side effects, because
|
|
4
|
+
* a retried click or fill could apply twice.
|
|
5
|
+
*/
|
|
6
|
+
const CLOSED_BY_NAVIGATION = /back\/forward cache|message channel is closed|message port closed/i;
|
|
7
|
+
export const NAVIGATION_RETRY_ATTEMPTS = 4;
|
|
8
|
+
const NAVIGATION_RETRY_MS = 250;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @template T
|
|
12
|
+
* @param {() => Promise<T>} read
|
|
13
|
+
* @param {{ attempts?: number, delayMs?: number }} [options]
|
|
14
|
+
* @returns {Promise<T>}
|
|
15
|
+
*/
|
|
16
|
+
export async function retryReadAcrossNavigation(read, { attempts = NAVIGATION_RETRY_ATTEMPTS, delayMs = NAVIGATION_RETRY_MS } = {}) {
|
|
17
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
18
|
+
try {
|
|
19
|
+
return await read();
|
|
20
|
+
} catch (error) {
|
|
21
|
+
const closedByNavigation = error instanceof Error && CLOSED_BY_NAVIGATION.test(error.message);
|
|
22
|
+
if (!closedByNavigation || attempt >= attempts) throw error;
|
|
23
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { NAVIGATION_RETRY_ATTEMPTS, retryReadAcrossNavigation } from './navigation-retry.js';
|
|
3
|
+
|
|
4
|
+
const closed = () => new Error('The page keeping the extension port is moved into back/forward cache, so the message channel is closed.');
|
|
5
|
+
|
|
6
|
+
describe('retryReadAcrossNavigation', () => {
|
|
7
|
+
test('retries until the read works', async () => {
|
|
8
|
+
let calls = 0;
|
|
9
|
+
const result = await retryReadAcrossNavigation(async () => { calls += 1; if (calls < 3) throw closed(); return 'ok'; }, { delayMs: 0 });
|
|
10
|
+
expect(result).toBe('ok');
|
|
11
|
+
expect(calls).toBe(3);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test('gives up after a bounded number of attempts', async () => {
|
|
15
|
+
let calls = 0;
|
|
16
|
+
await expect(retryReadAcrossNavigation(async () => { calls += 1; throw closed(); }, { delayMs: 0 })).rejects.toThrow('back/forward cache');
|
|
17
|
+
expect(calls).toBe(NAVIGATION_RETRY_ATTEMPTS);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('does not retry other errors', async () => {
|
|
21
|
+
let calls = 0;
|
|
22
|
+
await expect(retryReadAcrossNavigation(async () => { calls += 1; throw new Error('Element not found'); }, { delayMs: 0 })).rejects.toThrow('Element not found');
|
|
23
|
+
expect(calls).toBe(1);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export const LEDGER_DDL: string;
|
|
2
|
+
export interface OnboardingEnv { [key: string]: string | undefined }
|
|
3
|
+
export type Sql = (query: string, parameters?: readonly unknown[]) => Promise<any[]>;
|
|
4
|
+
export function onboardingConfig(env: OnboardingEnv): { since: string; sequenceId: string; version: number; recipients: string[] | null } | null;
|
|
5
|
+
export interface OnboardingSdk {
|
|
6
|
+
enroll(input: { sequenceId: string; version: number; subjectId: string; email: string; consent: true }): Promise<{ data: { id: string } }>;
|
|
7
|
+
getEnrollment(id: string): Promise<{ data: { status: string } }>;
|
|
8
|
+
track(input: { id: string; subjectId: string; name: string }): Promise<unknown>;
|
|
9
|
+
}
|
|
10
|
+
export interface SqlDatabase { executeQuery(query: { sql: string; parameters: readonly unknown[]; query: { kind: 'RawNode'; sqlFragments: string[]; parameters: unknown[] } }): Promise<{ rows: any[] }> }
|
|
11
|
+
export function onboardingSql(env: OnboardingEnv, createMechKysely: (options: { appId: string; apiKey: string }) => SqlDatabase): Sql;
|
|
12
|
+
export function queueVerifiedSignup(env: OnboardingEnv, subjectId: string, execute: (env: OnboardingEnv) => Sql): Promise<void>;
|
|
13
|
+
export function pumpOnboarding(options: { env: OnboardingEnv; sql: Sql; sdk: OnboardingSdk; completedTask: (subjectId: string, since: string) => Promise<boolean>; limit?: number }): Promise<{ enrolled: number; activated: number; failed: number }>;
|