@thinkrun/cli 0.1.39 → 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/scripts/browse.sh +40 -7
- 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/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/cloud.d.ts +2 -0
- package/dist/src/adapters/cloud.d.ts.map +1 -1
- package/dist/src/adapters/cloud.js +112 -17
- package/dist/src/adapters/cloud.js.map +1 -1
- package/dist/src/adapters/index.d.ts.map +1 -1
- package/dist/src/adapters/index.js +30 -5
- package/dist/src/adapters/index.js.map +1 -1
- package/dist/src/adapters/local.d.ts +3 -0
- package/dist/src/adapters/local.d.ts.map +1 -1
- package/dist/src/adapters/local.js +52 -13
- 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 +115 -28
- package/dist/src/commands/actions.js.map +1 -1
- package/dist/src/commands/analyze.d.ts.map +1 -1
- package/dist/src/commands/analyze.js +29 -1
- package/dist/src/commands/analyze.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/cloud.d.ts.map +1 -1
- package/dist/src/commands/cloud.js +3 -1
- package/dist/src/commands/cloud.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/evaluate-helpers.d.ts.map +1 -1
- package/dist/src/commands/evaluate-helpers.js +10 -2
- package/dist/src/commands/evaluate-helpers.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/local-bridge-timing.d.ts +3 -0
- package/dist/src/local-bridge-timing.d.ts.map +1 -1
- package/dist/src/local-bridge-timing.js +3 -0
- package/dist/src/local-bridge-timing.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/dist/src/types.d.ts +3 -1
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/utils.d.ts +9 -3
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/src/utils.js +24 -3
- package/dist/src/utils.js.map +1 -1
- package/dist/src/working-location.d.ts +1 -1
- package/dist/src/working-location.d.ts.map +1 -1
- package/dist/src/working-location.js +89 -67
- package/dist/src/working-location.js.map +1 -1
- package/package.json +3 -2
- package/skills/thinkrun/SKILL.md +66 -0
|
@@ -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 }>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Specialized delivery ledger for this one onboarding sequence. No runtime DDL.
|
|
2
|
+
export const LEDGER_DDL = `CREATE TABLE circleinbox_onboarding (
|
|
3
|
+
subject_id TEXT PRIMARY KEY, email TEXT NOT NULL,
|
|
4
|
+
enrollment_id TEXT, enrolled_at TIMESTAMPTZ, activated_at TIMESTAMPTZ, finished_at TIMESTAMPTZ,
|
|
5
|
+
checked_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
6
|
+
)`;
|
|
7
|
+
|
|
8
|
+
export function onboardingConfig(env) {
|
|
9
|
+
if (env.CIRCLEINBOX_ONBOARDING_ENABLED !== 'true') return null;
|
|
10
|
+
const since = new Date(env.CIRCLEINBOX_ONBOARDING_SINCE || '');
|
|
11
|
+
if (!Number.isFinite(since.getTime()) || env.CIRCLEINBOX_ONBOARDING_CONSENT !== 'true') {
|
|
12
|
+
throw new Error('Onboarding requires an explicit enable timestamp and consent assertion');
|
|
13
|
+
}
|
|
14
|
+
if (!env.CIRCLEINBOX_API_KEY || !Number.isSafeInteger(Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION)) || Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION) < 1) {
|
|
15
|
+
throw new Error('Onboarding requires credentials and a published sequence version');
|
|
16
|
+
}
|
|
17
|
+
const allowAll = env.CIRCLEINBOX_ONBOARDING_ALLOW_ALL_NEW_USERS === 'true';
|
|
18
|
+
const raw = env.CIRCLEINBOX_ONBOARDING_RECIPIENT_ALLOWLIST?.trim() || '';
|
|
19
|
+
if (allowAll === Boolean(raw) || raw.length > 5100) throw new Error('Onboarding requires exactly one recipient scope');
|
|
20
|
+
const recipients = raw ? [...new Set(raw.split(',').map((email) => email.trim().toLowerCase()))] : null;
|
|
21
|
+
if (recipients && (recipients.length > 20 || recipients.some((email) => email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)))) {
|
|
22
|
+
throw new Error('Onboarding recipient allowlist must contain 1 to 20 valid emails');
|
|
23
|
+
}
|
|
24
|
+
return { since: since.toISOString(), sequenceId: 'thinkrun-onboarding', version: Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION), recipients };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function onboardingSql(env, createMechKysely) {
|
|
28
|
+
const db = createMechKysely({ appId: env.MECH_APP_ID || env.MECH_BROWSE_APP_ID || '', apiKey: env.MECH_API_KEY });
|
|
29
|
+
return async (sql, parameters = []) => {
|
|
30
|
+
// executeQuery accepts this CompiledQuery directly; SQL is already compiled and bound.
|
|
31
|
+
const result = await db.executeQuery({ sql, parameters, query: { kind: 'RawNode', sqlFragments: [sql], parameters: [] } });
|
|
32
|
+
return result.rows;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function queueVerifiedSignup(env, subjectId, execute) {
|
|
37
|
+
const config = onboardingConfig(env);
|
|
38
|
+
if (!config) return;
|
|
39
|
+
const sql = execute(env);
|
|
40
|
+
// A successful verification is the source of truth; do not trust request email.
|
|
41
|
+
await sql(`INSERT INTO circleinbox_onboarding (subject_id,email)
|
|
42
|
+
SELECT id::text,email FROM users WHERE id=$1 AND email_verified=true AND created_at >= $2::timestamptz
|
|
43
|
+
AND ($3::text[] IS NULL OR lower(email)=ANY($3::text[]))
|
|
44
|
+
ON CONFLICT (subject_id) DO NOTHING`, [subjectId, config.since, config.recipients]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function pumpOnboarding({ env, sql, sdk, completedTask, limit = 25 }) {
|
|
48
|
+
const config = onboardingConfig(env);
|
|
49
|
+
if (!config) return { enrolled: 0, activated: 0, failed: 0 };
|
|
50
|
+
// Commit queued ledger rows BEFORE any remote SDK call, even during an outage.
|
|
51
|
+
// Exclude every queued subject (including enrolled_at=null); the next pass can
|
|
52
|
+
// discover users beyond this batch while earlier deliveries remain pending.
|
|
53
|
+
// This closes the post-auth enqueue gap for newly created verified accounts.
|
|
54
|
+
await sql(`INSERT INTO circleinbox_onboarding (subject_id,email)
|
|
55
|
+
SELECT u.id::text,u.email FROM users u WHERE u.email_verified=true AND u.created_at >= $1::timestamptz
|
|
56
|
+
AND ($2::text[] IS NULL OR lower(u.email)=ANY($2::text[]))
|
|
57
|
+
AND NOT EXISTS (SELECT 1 FROM circleinbox_onboarding o WHERE o.subject_id=u.id::text)
|
|
58
|
+
ORDER BY u.created_at,u.id LIMIT 100 ON CONFLICT (subject_id) DO NOTHING`, [config.since, config.recipients]);
|
|
59
|
+
const rows = await sql(`SELECT subject_id,email,enrolled_at,enrollment_id FROM circleinbox_onboarding
|
|
60
|
+
WHERE activated_at IS NULL AND finished_at IS NULL
|
|
61
|
+
AND ($2::text[] IS NULL OR lower(email)=ANY($2::text[]))
|
|
62
|
+
ORDER BY checked_at,subject_id LIMIT $1`, [limit, config.recipients]);
|
|
63
|
+
const result = { enrolled: 0, activated: 0, failed: 0 };
|
|
64
|
+
for (const row of rows) {
|
|
65
|
+
let failed = false;
|
|
66
|
+
try {
|
|
67
|
+
let enrollmentId = row.enrollment_id;
|
|
68
|
+
if (!row.enrolled_at || !enrollmentId) {
|
|
69
|
+
// API contract: UNIQUE(org,sequenceId,subjectId) across versions. Identical
|
|
70
|
+
// enroll replays return the same resource; changed payloads return409.
|
|
71
|
+
// Replaying after a lost ledger acknowledgment cannot create another workflow.
|
|
72
|
+
const enrollment = await sdk.enroll({ sequenceId: config.sequenceId, version: config.version, subjectId: row.subject_id, email: row.email, consent: true });
|
|
73
|
+
enrollmentId = enrollment?.data?.id;
|
|
74
|
+
if (typeof enrollmentId !== 'string' || !enrollmentId) throw new Error('InvalidEnrollmentResponse');
|
|
75
|
+
await sql('UPDATE circleinbox_onboarding SET enrolled_at=CURRENT_TIMESTAMP,enrollment_id=$2 WHERE subject_id=$1', [row.subject_id, enrollmentId]);
|
|
76
|
+
result.enrolled++;
|
|
77
|
+
}
|
|
78
|
+
const remote = await sdk.getEnrollment(enrollmentId);
|
|
79
|
+
if (['completed', 'cancelled', 'suppressed', 'failed', 'unknown'].includes(remote?.data?.status)) {
|
|
80
|
+
await sql('UPDATE circleinbox_onboarding SET finished_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!['active', 'waiting', 'sending'].includes(remote?.data?.status)) throw new Error('InvalidEnrollmentResponse');
|
|
84
|
+
if (await completedTask(row.subject_id, config.since)) {
|
|
85
|
+
await sdk.track({ id: `thinkrun:activated:${row.subject_id}`, subjectId: row.subject_id, name: 'thinkrun.task_completed' });
|
|
86
|
+
await sql('UPDATE circleinbox_onboarding SET activated_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]);
|
|
87
|
+
result.activated++;
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
// Status remains pending; retry uses stable enrollment/event identifiers.
|
|
91
|
+
failed = true;
|
|
92
|
+
result.failed++;
|
|
93
|
+
} finally {
|
|
94
|
+
try { await sql('UPDATE circleinbox_onboarding SET checked_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]); }
|
|
95
|
+
catch { if (!failed) result.failed++; }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
type Source = 'cli' | 'mcp';
|
|
2
|
+
type Step = 'local_connected' | 'account_connected' | 'session_saved';
|
|
3
|
+
export function onboardingReviewLink(source: Source, sessionId: string): string;
|
|
4
|
+
export function recordOnboardingStep(source: Source, step: Step, sessionId?: string): Promise<void>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Opt-in only. A missing receipt or unavailable collector must never interrupt browser control.
|
|
2
|
+
import { createHmac, randomUUID } from 'node:crypto';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
|
|
6
|
+
|
|
7
|
+
const endpoint = 'https://thinkrun.ai/api/onboarding-metrics';
|
|
8
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
9
|
+
const enabled = () => process.env.THINKRUN_ONBOARDING_METRICS === '1' && !process.env.DO_NOT_TRACK;
|
|
10
|
+
|
|
11
|
+
function install(source) {
|
|
12
|
+
if (!enabled() || !['cli', 'mcp'].includes(source)) return;
|
|
13
|
+
const base = join(process.env.THINKRUN_LOCK_DIR || join(homedir(), '.thinkrun'), 'onboarding-metrics');
|
|
14
|
+
const directory = join(base, source);
|
|
15
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
16
|
+
const file = join(base, 'installation');
|
|
17
|
+
if (!existsSync(file)) {
|
|
18
|
+
try { writeFileSync(file, randomUUID(), { flag: 'wx', mode: 0o600 }); }
|
|
19
|
+
catch (err) { if (err?.code !== 'EEXIST') throw err; }
|
|
20
|
+
}
|
|
21
|
+
const id = readFileSync(file, 'utf8');
|
|
22
|
+
if (uuid.test(id)) return { id, directory };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function reviewMarker(id, sessionId) {
|
|
26
|
+
return createHmac('sha256', id).update('review:' + sessionId).digest('hex').slice(0, 32);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function onboardingReviewLink(source, sessionId) {
|
|
30
|
+
const url = new URL('/sessions/' + encodeURIComponent(sessionId), 'https://thinkrun.ai');
|
|
31
|
+
try {
|
|
32
|
+
const installation = install(source);
|
|
33
|
+
if (installation) url.hash = 'tr-review=' + source + '.' + reviewMarker(installation.id, sessionId);
|
|
34
|
+
} catch { /* Prefer a clean dashboard link if metrics are unavailable. */ }
|
|
35
|
+
return url.href;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function recordOnboardingStep(source, step, sessionId) {
|
|
39
|
+
if (!['local_connected', 'account_connected', 'session_saved'].includes(step)) return;
|
|
40
|
+
try {
|
|
41
|
+
const installation = install(source);
|
|
42
|
+
if (!installation) return;
|
|
43
|
+
const review = step === 'session_saved' && sessionId ? reviewMarker(installation.id, sessionId) : undefined;
|
|
44
|
+
const receipt = join(installation.directory, review || step);
|
|
45
|
+
if (existsSync(receipt)) return;
|
|
46
|
+
const response = await fetch(endpoint, {
|
|
47
|
+
method: 'POST', redirect: 'error', credentials: 'omit', signal: AbortSignal.timeout(800),
|
|
48
|
+
headers: { 'Content-Type': 'application/json' },
|
|
49
|
+
body: JSON.stringify({ source, step, installation: installation.id, review }),
|
|
50
|
+
});
|
|
51
|
+
if (response.ok) writeFileSync(receipt, '', { mode: 0o600 });
|
|
52
|
+
} catch { /* Optional metrics are best effort. */ }
|
|
53
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function explainUnsupportedSelector(selector: string, action: string): string | null;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local mode resolves CSS plus Playwright's :has-text(), :text(), :text-is() and text=.
|
|
3
|
+
* Models also write other Playwright forms, so explain the fix before any round trip.
|
|
4
|
+
* Cloud mode runs real Playwright and should not use this check.
|
|
5
|
+
*/
|
|
6
|
+
const QUOTED = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g;
|
|
7
|
+
|
|
8
|
+
function roleNameText(selector) {
|
|
9
|
+
const match = selector.match(/^\s*[a-z]+\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*$/i);
|
|
10
|
+
return match ? match[1].slice(1, -1).replace(/\\(.)/g, '$1') : null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function usesUnsupportedSyntax(selector) {
|
|
14
|
+
// Remove quoted text first, so a CSS attribute value such as [title=":visible"] is not flagged.
|
|
15
|
+
const unquoted = selector.replace(QUOTED, '""');
|
|
16
|
+
const textPseudos = unquoted.match(/:(?:has-text|text-is|text)\(/g) ?? [];
|
|
17
|
+
return /^\s*text=\/.*\/[a-z]*\s*$/i.test(selector)
|
|
18
|
+
|| textPseudos.length > 1
|
|
19
|
+
|| /:(?:has-text|text-is|text)\(\s*[^"\s)]/.test(unquoted)
|
|
20
|
+
|| /:(?:has-text|text-is|text)\(\s*""\s*\)[^\s>]/.test(unquoted)
|
|
21
|
+
|| (textPseudos.length > 0 && /,/.test(unquoted.replace(/\([^()]*\)/g, '').replace(/\[[^\]]*\]/g, '')))
|
|
22
|
+
|| /:(?:text-matches|nth-match)\(/.test(unquoted)
|
|
23
|
+
|| /:visible\b/.test(unquoted)
|
|
24
|
+
|| /\s>>\s/.test(unquoted)
|
|
25
|
+
|| /\bgetBy[A-Z]\w*\(/.test(unquoted)
|
|
26
|
+
|| /:(?:right-of|left-of|above|below|near)\(/.test(unquoted)
|
|
27
|
+
|| /^\s*(?:role|css|xpath|id|data-testid|nth|internal:[\w-]+)=/i.test(unquoted)
|
|
28
|
+
|| /^\s*\(?\/\//.test(unquoted)
|
|
29
|
+
|| /^\s*[a-z]+\s+""\s*$/i.test(unquoted);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {string} selector
|
|
34
|
+
* @param {string} _action
|
|
35
|
+
* @returns {string | null} Guidance when the selector cannot work in local mode.
|
|
36
|
+
*/
|
|
37
|
+
export function explainUnsupportedSelector(selector, _action) {
|
|
38
|
+
if (typeof selector !== 'string') return null;
|
|
39
|
+
const trimmed = selector.trim();
|
|
40
|
+
if (!usesUnsupportedSyntax(trimmed)) return null;
|
|
41
|
+
const example = `:has-text("${roleNameText(trimmed) ?? 'Visible text'}")`;
|
|
42
|
+
return `Selector ${JSON.stringify(selector)} uses Playwright syntax that local mode does not support. Use a CSS selector, or match by text with ${example}.`;
|
|
43
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { explainUnsupportedSelector as explain } from './selector-hints.js';
|
|
3
|
+
|
|
4
|
+
describe('explainUnsupportedSelector', () => {
|
|
5
|
+
test.each([
|
|
6
|
+
'input[name=quantity]', 'form button[type=submit]', 'a[href="/product/2"]', 'div > a', 'li:nth-child(2)', 'a:not(.x)', 'input:checked',
|
|
7
|
+
'[title=":visible"]', '[data-x="a >> b"]', 'button:has(svg)',
|
|
8
|
+
'button:has-text("Add to cart")', "button:has-text('Add')", 'a:text("Next")', 'a:text-is("Next")', 'text=Add to cart', 'text="Add"',
|
|
9
|
+
'li:has-text("Speaker") a', 'li:has-text("Speaker") > a', ':is(a, button):has-text("x")', 'a, button',
|
|
10
|
+
])('allows %s', (selector) => {
|
|
11
|
+
expect(explain(selector, 'click')).toBeNull();
|
|
12
|
+
expect(explain(selector, 'fill')).toBeNull();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test.each([
|
|
16
|
+
'textbox "Search"', 'button:visible', 'a:visible', 'div >> a', 'getByRole("button")', 'role=button[name="Add"]', 'xpath=//a', 'css=a', 'id=main',
|
|
17
|
+
'data-testid=save', '//a[@href]', 'a:near(.x)', 'text=/add/i', 'a:has-text("x"):has-text("y")', 'a:has-text("x").y', 'a:has-text(x)', 'li:has-text("x") a, .other', 'li, .notice:has-text("x")',
|
|
18
|
+
])('explains %s', (selector) => {
|
|
19
|
+
const hint = explain(selector, 'fill');
|
|
20
|
+
expect(hint).toContain('Playwright syntax');
|
|
21
|
+
expect(hint).toContain(':has-text');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('uses the name from a role-style selector', () => {
|
|
25
|
+
expect(explain('button "Search"', 'click')).toContain(':has-text("Search")');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('ignores missing selectors', () => {
|
|
29
|
+
expect(explain(undefined, 'click')).toBeNull();
|
|
30
|
+
});
|
|
31
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const SLACK_REPORT_TITLE_LIMIT: 256;
|
|
2
|
+
export const SLACK_REPORT_BODY_LIMIT: 12000;
|
|
3
|
+
export type SlackReportMode = 'compact' | 'full';
|
|
4
|
+
export const SLACK_REPORT_MODES: SlackReportMode[];
|
|
5
|
+
export type SlackTextStyle = { bold?: boolean; italic?: boolean; code?: boolean };
|
|
6
|
+
export type SlackInline = { type: 'text'; text: string; style?: SlackTextStyle } | { type: 'link'; url: string; text: string; style?: SlackTextStyle };
|
|
7
|
+
export interface SlackRichSection { type: 'rich_text_section'; elements: SlackInline[] }
|
|
8
|
+
export type SlackRichElement = SlackRichSection
|
|
9
|
+
| { type: 'rich_text_list'; style: 'bullet' | 'ordered'; indent: number; offset?: number; elements: SlackRichSection[] }
|
|
10
|
+
| { type: 'rich_text_preformatted'; elements: SlackInline[] }
|
|
11
|
+
| { type: 'rich_text_quote'; elements: SlackInline[] };
|
|
12
|
+
export type SlackBlock = { type: 'header'; text: { type: 'plain_text'; text: string; emoji: false } }
|
|
13
|
+
| { type: 'rich_text'; elements: SlackRichElement[] }
|
|
14
|
+
| { type: 'divider' };
|
|
15
|
+
export interface SlackReportMessage { text: string; blocks: SlackBlock[]; mrkdwn: false; parse: 'none'; link_names: false; unfurl_links: false; unfurl_media: false }
|
|
16
|
+
export class SlackReportError extends Error { code: 'INVALID_MODE' | 'REPORT_TOO_LARGE'; constructor(code: string, message: string) }
|
|
17
|
+
export function safeSlackLinkUrl(value: unknown): string | undefined;
|
|
18
|
+
/** A projector's `message` is the exact chat.postMessage content; `notices` are preview-only disclosures. */
|
|
19
|
+
export type SlackReportProjector = (title: string, body: string, mode: SlackReportMode) => { message: SlackReportMessage; notices: string[] };
|
|
20
|
+
/** Pass `fromMarkdown` from `mdast-util-from-markdown`; consumers pin the same version for preview/delivery parity. */
|
|
21
|
+
export function createSlackReportProjector(fromMarkdown: (markdown: string) => unknown): SlackReportProjector;
|