@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,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 const ONBOARDING_PUBLIC_DEFAULT_CONSENT_VERSION: string;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export const MAX_RECORDING_UPLOAD_BYTES: number;
|
|
2
|
+
export class RecordingUploadError extends Error { code: string; }
|
|
3
|
+
export interface RecordingUploadFile { path: string; filename: string; sizeBytes: number; device: number; inode: number; contentType: 'video/webm' | 'video/mp4' | 'video/quicktime'; }
|
|
4
|
+
export function inspectRecordingUploadFile(path: string): Promise<RecordingUploadFile>;
|
|
5
|
+
export function uploadRecordingFile(options: { path: string; apiBase: string; apiKey?: string; intent?: string; title?: string; url?: string; dryRun?: boolean; fetchImpl?: typeof fetch }): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-facing local recording upload. This module deliberately accepts a path,
|
|
3
|
+
* never media bytes supplied by an API caller, and talks to the recording API
|
|
4
|
+
* directly (not through the browser extension/native bridge).
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { createReadStream } from 'node:fs';
|
|
8
|
+
import { access, lstat, open } from 'node:fs/promises';
|
|
9
|
+
import { constants } from 'node:fs';
|
|
10
|
+
import { basename, extname, resolve } from 'node:path';
|
|
11
|
+
import axios from 'axios';
|
|
12
|
+
|
|
13
|
+
export const MAX_RECORDING_UPLOAD_BYTES = 5 * 1024 * 1024 * 1024;
|
|
14
|
+
const MIME_BY_EXTENSION = Object.freeze({ '.webm': 'video/webm', '.mp4': 'video/mp4', '.mov': 'video/quicktime' });
|
|
15
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
16
|
+
const UPLOAD_TIMEOUT_MS = 30 * 60_000;
|
|
17
|
+
const CLEANUP_TIMEOUT_MS = 5_000;
|
|
18
|
+
|
|
19
|
+
export class RecordingUploadError extends Error {
|
|
20
|
+
constructor(code, message) { super(message); this.name = 'RecordingUploadError'; this.code = code; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function safeMessage(value, fallback) {
|
|
24
|
+
const text = String(value || fallback)
|
|
25
|
+
.replace(/https?:\/\/[^\s"']+/gi, '[redacted-url]')
|
|
26
|
+
.replace(/\bauthorization\s*[:=]\s*(?:bearer\s+)?[^\s,;]+/gi, 'Authorization: [redacted]')
|
|
27
|
+
.replace(/\b(?:uploadToken|api[_-]?key|authorization)\s*[:=]\s*[^\s,;]+/gi, '[redacted-credential]')
|
|
28
|
+
.replace(/"(?:uploadToken|api[_-]?key|authorization)"\s*:\s*"[^"]*"/gi, '"[redacted-credential]"')
|
|
29
|
+
.replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [redacted]');
|
|
30
|
+
return text.slice(0, 500);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function inspectRecordingUploadFile(path) {
|
|
34
|
+
if (typeof path !== 'string' || !path.trim()) throw new RecordingUploadError('INVALID_PATH', 'A non-empty local file path is required');
|
|
35
|
+
const resolvedPath = resolve(path);
|
|
36
|
+
let info;
|
|
37
|
+
try { info = await lstat(resolvedPath); await access(resolvedPath, constants.R_OK); }
|
|
38
|
+
catch { throw new RecordingUploadError('FILE_NOT_READABLE', 'Recording file is not readable'); }
|
|
39
|
+
if (info.isSymbolicLink()) throw new RecordingUploadError('SYMLINK_NOT_ALLOWED', 'Recording path must not be a symbolic link');
|
|
40
|
+
if (!info.isFile()) throw new RecordingUploadError('NOT_A_REGULAR_FILE', 'Recording path must be a regular readable file');
|
|
41
|
+
const contentType = MIME_BY_EXTENSION[extname(resolvedPath).toLowerCase()];
|
|
42
|
+
if (!contentType) throw new RecordingUploadError('UNSUPPORTED_MEDIA_TYPE', 'Recording must be a .webm, .mp4, or .mov file');
|
|
43
|
+
if (info.size > MAX_RECORDING_UPLOAD_BYTES) throw new RecordingUploadError('FILE_TOO_LARGE', 'Recording exceeds the 5 GiB upload limit');
|
|
44
|
+
return { path: resolvedPath, filename: basename(resolvedPath), sizeBytes: info.size, device: info.dev, inode: info.ino, contentType };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function headers(apiKey, contentType = 'application/json') {
|
|
48
|
+
const result = { 'Content-Type': contentType };
|
|
49
|
+
const key = apiKey?.trim();
|
|
50
|
+
if (key) { result['X-API-Key'] = key; result.Authorization = `Bearer ${key}`; }
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function request(fetchImpl, url, options) {
|
|
55
|
+
const response = await fetchImpl(url, { ...options, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
56
|
+
if (!response.ok) throw new RecordingUploadError('API_ERROR', `Recording upload request failed (HTTP ${response.status})`);
|
|
57
|
+
return response.json();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function requireSuccess(payload, code, message) {
|
|
61
|
+
if (!payload?.success) throw new RecordingUploadError(code, message);
|
|
62
|
+
return payload;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// These failures occur before a socket can deliver upload bytes. Other thrown
|
|
66
|
+
// transport errors are deliberately treated as ambiguous and retained for the
|
|
67
|
+
// server-side recovery path; a response may have been lost after storage wrote.
|
|
68
|
+
function isDefinitivePreTransferError(error) {
|
|
69
|
+
return ['ENOTFOUND', 'ECONNREFUSED', 'ERR_INVALID_URL'].includes(error?.code);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function cleanup(fetchImpl, baseUrl, apiKey, recordingId) {
|
|
73
|
+
if (!recordingId) return;
|
|
74
|
+
try {
|
|
75
|
+
await Promise.race([
|
|
76
|
+
fetchImpl(`${baseUrl}/api/feedback/recordings/${encodeURIComponent(recordingId)}`, { method: 'DELETE', headers: headers(apiKey), signal: AbortSignal.timeout(CLEANUP_TIMEOUT_MS) }),
|
|
77
|
+
new Promise((resolve) => setTimeout(resolve, CLEANUP_TIMEOUT_MS)),
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
catch { /* owned-stub cleanup is intentionally best effort */ }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** @param {{ path:string, apiBase:string, apiKey?:string, intent?:string, title?:string, url?:string, dryRun?:boolean, fetchImpl?:typeof fetch }} options */
|
|
84
|
+
export async function uploadRecordingFile(options) {
|
|
85
|
+
const file = await inspectRecordingUploadFile(options.path);
|
|
86
|
+
const { device: _device, inode: _inode, ...publicFile } = file;
|
|
87
|
+
const intent = String(options.intent || 'feedback');
|
|
88
|
+
const title = String(options.title || file.filename);
|
|
89
|
+
if (intent.length > 200) throw new RecordingUploadError('INVALID_INTENT', 'Analysis intent must be 200 characters or fewer');
|
|
90
|
+
if (title.length > 500) throw new RecordingUploadError('INVALID_TITLE', 'Recording title must be 500 characters or fewer');
|
|
91
|
+
const url = options.url ? String(options.url) : '';
|
|
92
|
+
if (url) {
|
|
93
|
+
try { const parsed = new URL(url); if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('protocol'); }
|
|
94
|
+
catch { throw new RecordingUploadError('INVALID_URL', 'Associated URL must be an absolute http(s) URL'); }
|
|
95
|
+
}
|
|
96
|
+
if (options.dryRun) return { success: true, dryRun: true, source: 'cli', intent, title, url, ...publicFile };
|
|
97
|
+
const baseUrl = String(options.apiBase || '').replace(/\/$/, '');
|
|
98
|
+
if (!/^https?:\/\//.test(baseUrl)) throw new RecordingUploadError('INVALID_API_BASE', 'A valid API base URL is required');
|
|
99
|
+
const fetchImpl = options.fetchImpl || fetch;
|
|
100
|
+
let recordingId;
|
|
101
|
+
let uploadStarted = false;
|
|
102
|
+
let handle;
|
|
103
|
+
try {
|
|
104
|
+
// Open once after validation and stream that descriptor, preventing a path swap
|
|
105
|
+
// between inspection and upload. O_NOFOLLOW is an additional OS-level guard.
|
|
106
|
+
handle = await open(file.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
107
|
+
const opened = await handle.stat();
|
|
108
|
+
if (!opened.isFile() || opened.size !== file.sizeBytes || opened.dev !== file.device || opened.ino !== file.inode) throw new RecordingUploadError('FILE_CHANGED', 'Recording file changed during validation');
|
|
109
|
+
const stream = () => createReadStream(file.path, { fd: handle.fd, autoClose: false, start: 0 });
|
|
110
|
+
const digest = createHash('sha256');
|
|
111
|
+
for await (const chunk of stream()) digest.update(chunk);
|
|
112
|
+
const videoChecksumSha256 = digest.digest('hex');
|
|
113
|
+
const created = requireSuccess(await request(fetchImpl, `${baseUrl}/api/feedback/recordings`, {
|
|
114
|
+
method: 'POST', headers: headers(options.apiKey), body: JSON.stringify({
|
|
115
|
+
source: 'cli', videoContentType: file.contentType, videoBytes: file.sizeBytes, videoChecksumSha256,
|
|
116
|
+
metadata: { version: '1.0', duration: 0, url, title, profile: 'simple', intent, features: { audio: false, console: false, network: false, dom: false } },
|
|
117
|
+
actions: [], browserState: { consoleLogs: [], networkRequests: [] }, elements: [],
|
|
118
|
+
}),
|
|
119
|
+
}), 'CREATE_FAILED', 'Recording creation failed');
|
|
120
|
+
recordingId = created?.recordingId;
|
|
121
|
+
if (!created?.success || typeof recordingId !== 'string') throw new RecordingUploadError('CREATE_FAILED', 'Recording creation returned an invalid response');
|
|
122
|
+
let strategy = 'stream';
|
|
123
|
+
const directKeys = ['uploadUrl', 'uploadToken', 'presignedVideoObjectId'];
|
|
124
|
+
const directFields = directKeys.map((key) => created[key]);
|
|
125
|
+
if (directKeys.some((key) => Object.hasOwn(created, key)) && !directFields.every((value) => typeof value === 'string' && value.length > 0)) throw new RecordingUploadError('INVALID_DIRECT_UPLOAD_RESPONSE', 'Recording creation returned incomplete direct upload details');
|
|
126
|
+
if (directFields.every(Boolean)) {
|
|
127
|
+
strategy = 'direct';
|
|
128
|
+
// A dropped storage/finalize response can follow a successful write. Once
|
|
129
|
+
// upload begins, preserve the recording for recovery rather than deleting
|
|
130
|
+
// a valid upload and its queued analysis on an ambiguous outcome.
|
|
131
|
+
uploadStarted = true;
|
|
132
|
+
// Axios preserves Content-Length for Node file streams; fetch sends these
|
|
133
|
+
// as chunked bodies and R2's presigned endpoint rejects them with HTTP 411.
|
|
134
|
+
const directHeaders = new Headers(created.presignedVideoHeaders);
|
|
135
|
+
directHeaders.set('Content-Type', created.presignedVideoContentType || file.contentType);
|
|
136
|
+
directHeaders.set('Content-Length', String(file.sizeBytes));
|
|
137
|
+
let direct;
|
|
138
|
+
try {
|
|
139
|
+
direct = options.fetchImpl
|
|
140
|
+
? await fetchImpl(created.uploadUrl, { method: 'PUT', headers: directHeaders, body: stream(), duplex: 'half', signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS) })
|
|
141
|
+
: await axios.put(created.uploadUrl, stream(), { headers: { ...created.presignedVideoHeaders, 'Content-Type': created.presignedVideoContentType || file.contentType, 'Content-Length': String(file.sizeBytes) }, maxBodyLength: MAX_RECORDING_UPLOAD_BYTES, timeout: UPLOAD_TIMEOUT_MS, validateStatus: () => true });
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (isDefinitivePreTransferError(error)) uploadStarted = false;
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
const directSucceeded = typeof direct.ok === 'boolean'
|
|
147
|
+
? direct.ok
|
|
148
|
+
: typeof direct.status === 'number' && direct.status >= 200 && direct.status < 300;
|
|
149
|
+
if (!directSucceeded) {
|
|
150
|
+
// Only a client-side rejection is definitive. A 5xx can be emitted
|
|
151
|
+
// after storage accepted bytes, so preserve recovery state for it.
|
|
152
|
+
if (direct.status >= 400 && direct.status < 500 && direct.status !== 408) uploadStarted = false;
|
|
153
|
+
throw new RecordingUploadError('DIRECT_UPLOAD_FAILED', `Direct recording upload failed (HTTP ${direct.status})`);
|
|
154
|
+
}
|
|
155
|
+
const finalized = requireSuccess(await request(fetchImpl, `${baseUrl}/api/feedback/recordings/${encodeURIComponent(recordingId)}/video/complete`, { method: 'POST', headers: headers(options.apiKey), body: JSON.stringify({ objectId: created.presignedVideoObjectId, uploadToken: created.uploadToken, sizeBytes: file.sizeBytes }) }), 'FINALIZE_FAILED', 'Recording upload finalize failed');
|
|
156
|
+
return { success: Boolean(finalized?.success), recordingId, source: 'cli', uploadStrategy: strategy, analysisEnqueued: Boolean(finalized?.analysisEnqueued), analysisJobId: finalized?.analysisJobId || null, analysisStatus: finalized?.analysisStatus || null, warning: finalized?.analysisEnqueueError ? safeMessage(finalized.analysisEnqueueError, 'Analysis enqueue failed') : undefined };
|
|
157
|
+
}
|
|
158
|
+
uploadStarted = true;
|
|
159
|
+
let streamedResponse;
|
|
160
|
+
try {
|
|
161
|
+
streamedResponse = options.fetchImpl
|
|
162
|
+
? await fetchImpl(`${baseUrl}/api/feedback/recordings/${encodeURIComponent(recordingId)}/video`, { method: 'PUT', headers: { ...headers(options.apiKey, file.contentType), 'Content-Length': String(file.sizeBytes) }, body: stream(), duplex: 'half', signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS) })
|
|
163
|
+
: await axios.put(`${baseUrl}/api/feedback/recordings/${encodeURIComponent(recordingId)}/video`, stream(), { headers: { ...headers(options.apiKey, file.contentType), 'Content-Length': String(file.sizeBytes) }, maxBodyLength: MAX_RECORDING_UPLOAD_BYTES, timeout: UPLOAD_TIMEOUT_MS, validateStatus: () => true });
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (isDefinitivePreTransferError(error)) uploadStarted = false;
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
const streamSucceeded = typeof streamedResponse.ok === 'boolean'
|
|
169
|
+
? streamedResponse.ok
|
|
170
|
+
: typeof streamedResponse.status === 'number' && streamedResponse.status >= 200 && streamedResponse.status < 300;
|
|
171
|
+
if (!streamSucceeded) {
|
|
172
|
+
if (streamedResponse.status >= 400 && streamedResponse.status < 500 && streamedResponse.status !== 408) uploadStarted = false;
|
|
173
|
+
throw new RecordingUploadError('STREAM_UPLOAD_FAILED', `Streaming recording upload failed (HTTP ${streamedResponse.status})`);
|
|
174
|
+
}
|
|
175
|
+
const streamed = requireSuccess(typeof streamedResponse.json === 'function' ? await streamedResponse.json() : streamedResponse.data, 'STREAM_UPLOAD_FAILED', 'Streaming recording upload failed');
|
|
176
|
+
return { success: Boolean(streamed?.success), recordingId, source: 'cli', uploadStrategy: strategy, analysisEnqueued: Boolean(streamed?.analysisEnqueued), analysisJobId: streamed?.analysisJobId || null, analysisStatus: streamed?.analysisStatus || null, warning: streamed?.analysisEnqueueError ? safeMessage(streamed.analysisEnqueueError, 'Analysis enqueue failed') : undefined };
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if (!uploadStarted) await cleanup(fetchImpl, baseUrl, options.apiKey, recordingId);
|
|
179
|
+
if (error instanceof RecordingUploadError) throw error;
|
|
180
|
+
throw new RecordingUploadError('UPLOAD_FAILED', safeMessage(error?.message, 'Recording upload failed'));
|
|
181
|
+
} finally {
|
|
182
|
+
await handle?.close().catch(() => {});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtemp, writeFile, rm, symlink } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { inspectRecordingUploadFile, uploadRecordingFile } from './recording-upload.js';
|
|
6
|
+
|
|
7
|
+
const dirs = [];
|
|
8
|
+
async function fixture(name = 'capture.webm') {
|
|
9
|
+
const dir = await mkdtemp(join(tmpdir(), 'thinkrun-upload-')); dirs.push(dir);
|
|
10
|
+
const path = join(dir, name); await writeFile(path, 'video'); return path;
|
|
11
|
+
}
|
|
12
|
+
afterEach(async () => { await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); });
|
|
13
|
+
|
|
14
|
+
describe('agent recording upload', () => {
|
|
15
|
+
test('validates explicit file locally and dry run makes no request', async () => {
|
|
16
|
+
const path = await fixture();
|
|
17
|
+
expect(await inspectRecordingUploadFile(path)).toMatchObject({ contentType: 'video/webm', sizeBytes: 5 });
|
|
18
|
+
const result = await uploadRecordingFile({ path, dryRun: true, apiBase: 'https://api.example.test', fetchImpl: () => { throw new Error('network'); } });
|
|
19
|
+
expect(result).toMatchObject({ success: true, dryRun: true, source: 'cli', intent: 'feedback', contentType: 'video/webm' });
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('uses direct upload then finalizes without returning credentials', async () => {
|
|
23
|
+
const path = await fixture(); const calls = [];
|
|
24
|
+
const fetchImpl = async (url, init = {}) => {
|
|
25
|
+
calls.push({ url, init });
|
|
26
|
+
if (String(url).endsWith('/recordings')) return new Response(JSON.stringify({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/token', uploadToken: 'token-secret', presignedVideoObjectId: 'object-1', presignedVideoContentType: 'video/webm' }), { status: 200 });
|
|
27
|
+
if (String(url).startsWith('https://signed.')) return new Response('', { status: 200 });
|
|
28
|
+
return new Response(JSON.stringify({ success: true, analysisEnqueued: false, analysisStatus: 'enqueue_failed', analysisEnqueueError: 'queue unavailable https://secret.example.test' }), { status: 200 });
|
|
29
|
+
};
|
|
30
|
+
const result = await uploadRecordingFile({ path, apiBase: 'https://api.example.test', apiKey: 'do-not-leak', fetchImpl });
|
|
31
|
+
expect(result).toMatchObject({ success: true, recordingId: 'rec-12345678', uploadStrategy: 'direct', analysisEnqueued: false });
|
|
32
|
+
expect(JSON.stringify(result)).not.toContain('secret.example');
|
|
33
|
+
expect(JSON.stringify(result)).not.toContain('token-secret');
|
|
34
|
+
expect(calls).toHaveLength(3);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('normalizes supplied direct-upload header names without comma-joining values', async () => {
|
|
38
|
+
const path = await fixture(); let checked = false;
|
|
39
|
+
const fetchImpl = async (url, init = {}) => {
|
|
40
|
+
if (String(url).endsWith('/recordings')) return Response.json({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/token', uploadToken: 'token', presignedVideoObjectId: 'object-1', presignedVideoContentType: 'video/webm', presignedVideoHeaders: { 'content-type': 'video/webm', 'content-length': '5' } });
|
|
41
|
+
if (String(url).startsWith('https://signed.')) {
|
|
42
|
+
const headers = new Headers(init.headers);
|
|
43
|
+
expect(headers.get('content-type')).toBe('video/webm');
|
|
44
|
+
expect(headers.get('content-length')).toBe('5');
|
|
45
|
+
checked = true; return new Response('', { status: 200 });
|
|
46
|
+
}
|
|
47
|
+
return Response.json({ success: true, analysisEnqueued: false });
|
|
48
|
+
};
|
|
49
|
+
await uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl });
|
|
50
|
+
expect(checked).toBe(true);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('falls back to the authenticated streaming endpoint when no presign is offered', async () => {
|
|
54
|
+
const path = await fixture('capture.mov'); const calls = [];
|
|
55
|
+
const fetchImpl = async (url, init = {}) => {
|
|
56
|
+
calls.push({ url, init });
|
|
57
|
+
if (String(url).endsWith('/recordings')) return new Response(JSON.stringify({ success: true, recordingId: 'rec-12345678' }));
|
|
58
|
+
return new Response(JSON.stringify({ success: true, analysisEnqueued: true, analysisJobId: 'job-1', analysisStatus: 'queued' }));
|
|
59
|
+
};
|
|
60
|
+
const result = await uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl });
|
|
61
|
+
expect(result).toMatchObject({ success: true, uploadStrategy: 'stream', analysisEnqueued: true, analysisJobId: 'job-1' });
|
|
62
|
+
expect(calls[1].init.headers).toMatchObject({ 'Content-Type': 'video/quicktime', 'Content-Length': '5' });
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('uses the default Axios transport for streaming fallback responses', async () => {
|
|
66
|
+
const path = await fixture(); const requests = [];
|
|
67
|
+
const server = Bun.serve({ port: 0, async fetch(request) {
|
|
68
|
+
const url = new URL(request.url); requests.push({ path: url.pathname, method: request.method, contentLength: request.headers.get('content-length') });
|
|
69
|
+
if (request.method === 'POST' && url.pathname.endsWith('/recordings')) return Response.json({ success: true, recordingId: 'rec-12345678' });
|
|
70
|
+
if (request.method === 'PUT') { await request.arrayBuffer(); return Response.json({ success: true, analysisEnqueued: true, analysisJobId: 'job-1', analysisStatus: 'queued' }); }
|
|
71
|
+
return Response.json({ success: true });
|
|
72
|
+
} });
|
|
73
|
+
try {
|
|
74
|
+
const result = await uploadRecordingFile({ path, apiBase: `http://127.0.0.1:${server.port}` });
|
|
75
|
+
expect(result).toMatchObject({ success: true, uploadStrategy: 'stream', analysisEnqueued: true, analysisJobId: 'job-1' });
|
|
76
|
+
expect(requests[1]).toMatchObject({ method: 'PUT', contentLength: '5' });
|
|
77
|
+
} finally { server.stop(true); }
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('preserves an uploaded recording when direct finalization is ambiguous', async () => {
|
|
81
|
+
const path = await fixture(); const methods = [];
|
|
82
|
+
const fetchImpl = async (url, init = {}) => {
|
|
83
|
+
methods.push(init.method);
|
|
84
|
+
if (String(url).endsWith('/recordings')) return new Response(JSON.stringify({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/token', uploadToken: 'token', presignedVideoObjectId: 'object-1' }));
|
|
85
|
+
if (String(url).startsWith('https://signed.')) return new Response('', { status: 200 });
|
|
86
|
+
if (init.method === 'POST') return new Response(JSON.stringify({ success: false }), { status: 200 });
|
|
87
|
+
return new Response(JSON.stringify({ success: true }));
|
|
88
|
+
};
|
|
89
|
+
await expect(uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl })).rejects.toMatchObject({ code: 'FINALIZE_FAILED' });
|
|
90
|
+
expect(methods).toEqual(['POST', 'PUT', 'POST']);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('cleans up an owned stub after a definitive direct-upload rejection', async () => {
|
|
94
|
+
const path = await fixture(); const methods = [];
|
|
95
|
+
const fetchImpl = async (url, init = {}) => {
|
|
96
|
+
methods.push(init.method);
|
|
97
|
+
if (String(url).endsWith('/recordings')) return new Response(JSON.stringify({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/token', uploadToken: 'token', presignedVideoObjectId: 'object-1' }));
|
|
98
|
+
if (String(url).startsWith('https://signed.')) return new Response('', { status: 403 });
|
|
99
|
+
return new Response(JSON.stringify({ success: true }));
|
|
100
|
+
};
|
|
101
|
+
await expect(uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl })).rejects.toMatchObject({ code: 'DIRECT_UPLOAD_FAILED' });
|
|
102
|
+
expect(methods).toEqual(['POST', 'PUT', 'DELETE']);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test('preserves an owned recording after an ambiguous direct-upload server failure', async () => {
|
|
106
|
+
const path = await fixture(); const methods = [];
|
|
107
|
+
const fetchImpl = async (url, init = {}) => {
|
|
108
|
+
methods.push(init.method);
|
|
109
|
+
if (String(url).endsWith('/recordings')) return new Response(JSON.stringify({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/token', uploadToken: 'token', presignedVideoObjectId: 'object-1' }));
|
|
110
|
+
if (String(url).startsWith('https://signed.')) return new Response('', { status: 500 });
|
|
111
|
+
return new Response(JSON.stringify({ success: true }));
|
|
112
|
+
};
|
|
113
|
+
await expect(uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl })).rejects.toMatchObject({ code: 'DIRECT_UPLOAD_FAILED' });
|
|
114
|
+
expect(methods).toEqual(['POST', 'PUT']);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('cleans up after a definitive pre-transfer failure', async () => {
|
|
118
|
+
const path = await fixture(); const methods = [];
|
|
119
|
+
const fetchImpl = async (url, init = {}) => {
|
|
120
|
+
methods.push(init.method);
|
|
121
|
+
if (String(url).endsWith('/recordings')) return new Response(JSON.stringify({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/token', uploadToken: 'token', presignedVideoObjectId: 'object-1' }));
|
|
122
|
+
if (String(url).startsWith('https://signed.')) { const error = new Error('DNS failed'); error.code = 'ENOTFOUND'; throw error; }
|
|
123
|
+
return new Response(JSON.stringify({ success: true }));
|
|
124
|
+
};
|
|
125
|
+
await expect(uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl })).rejects.toMatchObject({ code: 'UPLOAD_FAILED' });
|
|
126
|
+
expect(methods).toEqual(['POST', 'PUT', 'DELETE']);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test('redacts credentials from generic upstream errors', async () => {
|
|
130
|
+
const path = await fixture();
|
|
131
|
+
const fetchImpl = async () => { throw new Error('Authorization: Bearer secret-value https://signed.example.test/upload?uploadToken=token-secret'); };
|
|
132
|
+
const error = await uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl }).catch((caught) => caught);
|
|
133
|
+
expect(error).toMatchObject({ code: 'UPLOAD_FAILED' });
|
|
134
|
+
expect(error.message).not.toContain('secret-value');
|
|
135
|
+
expect(error.message).not.toContain('signed.example');
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test('rejects unsafe paths and overlong metadata before creating a recording', async () => {
|
|
139
|
+
const path = await fixture();
|
|
140
|
+
const link = `${path}.webm`;
|
|
141
|
+
await symlink(path, link);
|
|
142
|
+
await expect(inspectRecordingUploadFile(link)).rejects.toMatchObject({ code: 'SYMLINK_NOT_ALLOWED' });
|
|
143
|
+
await expect(uploadRecordingFile({ path, dryRun: true, apiBase: 'https://api.example.test', intent: 'x'.repeat(201) })).rejects.toMatchObject({ code: 'INVALID_INTENT' });
|
|
144
|
+
await expect(uploadRecordingFile({ path, dryRun: true, apiBase: 'https://api.example.test', title: 'x'.repeat(501) })).rejects.toMatchObject({ code: 'INVALID_TITLE' });
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('cleans up and rejects a partial direct-upload response', async () => {
|
|
148
|
+
const path = await fixture(); const methods = [];
|
|
149
|
+
const fetchImpl = async (_url, init = {}) => {
|
|
150
|
+
methods.push(init.method);
|
|
151
|
+
if (init.method === 'POST') return new Response(JSON.stringify({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/secret' }));
|
|
152
|
+
return new Response(JSON.stringify({ success: true }));
|
|
153
|
+
};
|
|
154
|
+
await expect(uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl })).rejects.toMatchObject({ code: 'INVALID_DIRECT_UPLOAD_RESPONSE' });
|
|
155
|
+
expect(methods).toEqual(['POST', 'DELETE']);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -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;
|