Skip to content

Commit 0b2f560

Browse files
authored
Merge pull request #48 from SentienceAPI/improve_agent5
Save trace in snapshot
2 parents 1457340 + a2bc86f commit 0b2f560

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/snapshot.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
import { SentienceBrowser } from './browser';
66
import { Snapshot } from './types';
7+
import * as fs from 'fs';
8+
import * as path from 'path';
79

810
export interface SnapshotOptions {
911
screenshot?: boolean | { format: 'png' | 'jpeg'; quality?: number };
@@ -14,6 +16,30 @@ export interface SnapshotOptions {
1416
min_z_index?: number;
1517
};
1618
use_api?: boolean; // Force use of server-side API if True, local extension if False
19+
save_trace?: boolean; // Save raw_elements to JSON for benchmarking/training
20+
trace_path?: string; // Path to save trace file (default: "trace_{timestamp}.json")
21+
}
22+
23+
/**
24+
* Save raw_elements to a JSON file for benchmarking/training
25+
*
26+
* @param rawElements Raw elements data from snapshot
27+
* @param tracePath Path to save trace file. If undefined, uses "trace_{timestamp}.json"
28+
*/
29+
function _saveTraceToFile(rawElements: any[], tracePath?: string): void {
30+
// Default filename if none provided
31+
const filename = tracePath || `trace_${Date.now()}.json`;
32+
33+
// Ensure directory exists
34+
const dir = path.dirname(filename);
35+
if (dir !== '.') {
36+
fs.mkdirSync(dir, { recursive: true });
37+
}
38+
39+
// Save the raw elements to JSON
40+
fs.writeFileSync(filename, JSON.stringify(rawElements, null, 2));
41+
42+
console.log(`[SDK] Trace saved to: ${filename}`);
1743
}
1844

1945
export async function snapshot(
@@ -83,6 +109,11 @@ async function snapshotViaExtension(
83109
return window.sentience.snapshot(opts);
84110
}, opts);
85111

112+
// Save trace if requested
113+
if (options.save_trace && result.raw_elements) {
114+
_saveTraceToFile(result.raw_elements, options.trace_path);
115+
}
116+
86117
// Basic validation
87118
if (result.status !== 'success' && result.status !== 'error') {
88119
throw new Error(`Invalid snapshot status: ${result.status}`);
@@ -122,6 +153,11 @@ async function snapshotViaApi(
122153
return (window as any).sentience.snapshot(opts);
123154
}, rawOpts);
124155

156+
// Save trace if requested (save raw data before API processing)
157+
if (options.save_trace && rawResult.raw_elements) {
158+
_saveTraceToFile(rawResult.raw_elements, options.trace_path);
159+
}
160+
125161
// Step 2: Send to server for smart ranking/filtering
126162
// Use raw_elements (raw data) instead of elements (processed data)
127163
// Server validates API key and applies proprietary ranking logic

0 commit comments

Comments
 (0)