-
Notifications
You must be signed in to change notification settings - Fork 296
Expand file tree
/
Copy pathbrowserbase.service.ts
More file actions
918 lines (808 loc) · 25.5 KB
/
browserbase.service.ts
File metadata and controls
918 lines (808 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
import { Injectable, Logger } from '@nestjs/common';
import Browserbase from '@browserbasehq/sdk';
// Lazy-imported in createStagehand() to avoid Node v25 crash
// (SlowBuffer.prototype was removed — @browserbasehq/stagehand bundles buffer-equal-constant-time which uses it)
type Stagehand = import('@browserbasehq/stagehand').Stagehand;
import { db } from '@db';
import { z } from 'zod';
import {
GetObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const BROWSER_WIDTH = 1440;
const BROWSER_HEIGHT = 900;
/** Stagehand v3 requires 'provider/model' format. */
const STAGEHAND_MODEL = 'anthropic/claude-sonnet-4-6';
const STAGEHAND_CUA_MODEL = 'anthropic/claude-sonnet-4-6';
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const PENDING_CONTEXT_ID = '__PENDING__';
const isPrismaUniqueConstraintError = (error: unknown): boolean => {
if (typeof error !== 'object' || error === null) return false;
if (!('code' in error)) return false;
const code = (error as { code?: unknown }).code;
return code === 'P2002';
};
@Injectable()
export class BrowserbaseService {
private readonly logger = new Logger(BrowserbaseService.name);
private readonly s3Client: S3Client;
private readonly bucketName: string;
constructor() {
this.s3Client = new S3Client({
region: process.env.AWS_REGION || 'us-east-1',
});
this.bucketName = process.env.APP_AWS_BUCKET_NAME || 'comp-attachments';
}
private getBrowserbase() {
return new Browserbase({
apiKey: process.env.BROWSERBASE_API_KEY,
});
}
private getProjectId() {
return process.env.BROWSERBASE_PROJECT_ID || '';
}
/**
* Stagehand sometimes has no active page (or the page gets closed mid-run),
* which causes errors like: "No Page found for awaitActivePage: no page available".
* Ensure there's at least one non-closed page available, and create one if needed.
*/
private async ensureActivePage(stagehand: Stagehand) {
const MAX_WAIT_MS = 5000;
const POLL_MS = 250;
const startedAt = Date.now();
while (Date.now() - startedAt < MAX_WAIT_MS) {
// Stagehand's Page type doesn't always expose Playwright's `isClosed()` in typings.
// We still want to filter out closed pages at runtime when possible.
const pages = stagehand.context.pages().filter((p) => {
const maybeIsClosed = (p as { isClosed?: () => boolean }).isClosed;
return typeof maybeIsClosed === 'function' ? !maybeIsClosed() : true;
});
if (pages[0]) return pages[0];
await delay(POLL_MS);
}
// Last resort: create a page (may still fail if the CDP session already died)
return await stagehand.context.newPage();
}
// ===== Organization Context Management =====
async getOrCreateOrgContext(
organizationId: string,
): Promise<{ contextId: string; isNew: boolean }> {
// Fast path: already created
const existing = await db.browserbaseContext.findUnique({
where: { organizationId },
});
if (existing && existing.contextId !== PENDING_CONTEXT_ID) {
return { contextId: existing.contextId, isNew: false };
}
try {
await db.browserbaseContext.create({
data: {
organizationId,
contextId: PENDING_CONTEXT_ID,
},
});
const bb = this.getBrowserbase();
const context = await bb.contexts.create({
projectId: this.getProjectId(),
});
await db.browserbaseContext.update({
where: { organizationId },
data: { contextId: context.id },
});
return { contextId: context.id, isNew: true };
} catch (error) {
if (!isPrismaUniqueConstraintError(error)) {
throw error;
}
}
const MAX_WAIT_MS = 10_000;
const POLL_MS = 200;
const startedAt = Date.now();
while (Date.now() - startedAt < MAX_WAIT_MS) {
const current = await db.browserbaseContext.findUnique({
where: { organizationId },
});
if (current && current.contextId !== PENDING_CONTEXT_ID) {
return { contextId: current.contextId, isNew: false };
}
if (!current) {
return await this.getOrCreateOrgContext(organizationId);
}
await delay(POLL_MS);
}
this.logger.warn(
`Timed out waiting for Browserbase context creation for org ${organizationId}`,
);
throw new Error(
'Browser context initialization is taking too long. Please retry.',
);
}
async getOrgContext(
organizationId: string,
): Promise<{ contextId: string } | null> {
const context = await db.browserbaseContext.findUnique({
where: { organizationId },
});
if (!context) return null;
return { contextId: context.contextId };
}
// ===== Session Management =====
async createSessionWithContext(
contextId: string,
): Promise<{ sessionId: string; liveViewUrl: string }> {
const bb = this.getBrowserbase();
const session = await bb.sessions.create({
projectId: this.getProjectId(),
browserSettings: {
context: {
id: contextId,
persist: true,
},
fingerprint: {
screen: {
maxHeight: BROWSER_HEIGHT,
maxWidth: BROWSER_WIDTH,
minHeight: BROWSER_HEIGHT,
minWidth: BROWSER_WIDTH,
},
},
viewport: { width: BROWSER_WIDTH, height: BROWSER_HEIGHT },
},
keepAlive: true,
});
const debug = await bb.sessions.debug(session.id);
return {
sessionId: session.id,
liveViewUrl: debug.debuggerFullscreenUrl,
};
}
async closeSession(sessionId: string): Promise<void> {
const bb = this.getBrowserbase();
await bb.sessions.update(sessionId, {
projectId: this.getProjectId(),
status: 'REQUEST_RELEASE',
});
}
// ===== Stagehand helpers =====
private async createStagehand(sessionId: string): Promise<Stagehand> {
const { Stagehand } = await import('@browserbasehq/stagehand');
const stagehand = new Stagehand({
env: 'BROWSERBASE',
apiKey: process.env.BROWSERBASE_API_KEY,
projectId: this.getProjectId(),
browserbaseSessionID: sessionId,
model: {
modelName: STAGEHAND_MODEL,
apiKey: process.env.ANTHROPIC_API_KEY,
},
verbose: 1,
});
await stagehand.init();
return stagehand;
}
private async safeCloseStagehand(stagehand: Stagehand) {
try {
await stagehand.close();
} catch (err) {
// IMPORTANT: never let cleanup errors override a successful run
this.logger.warn('Failed to close stagehand (ignored)', {
error: err instanceof Error ? err.message : String(err),
});
}
}
// ===== Browser Actions =====
async navigateToUrl(
sessionId: string,
url: string,
): Promise<{ success: boolean; error?: string }> {
let stagehand: Stagehand | null = null;
try {
stagehand = await this.createStagehand(sessionId);
const page = stagehand.context.pages()[0];
if (!page) {
throw new Error('No page found in browser session');
}
// Set up virtual authenticator to bypass passkeys via CDP
await page.sendCDP('WebAuthn.enable');
await page.sendCDP('WebAuthn.addVirtualAuthenticator', {
options: {
protocol: 'ctap2',
transport: 'internal',
hasResidentKey: true,
hasUserVerification: true,
isUserVerified: true,
automaticPresenceSimulation: true,
},
});
await page.goto(url, {
waitUntil: 'domcontentloaded',
timeoutMs: 30000,
});
return { success: true };
} catch (err) {
this.logger.error('Failed to navigate to URL', err);
if (stagehand) {
try {
await stagehand.close();
} catch (closeErr) {
this.logger.warn('Failed to close stagehand after navigation error', {
closeErr:
closeErr instanceof Error
? closeErr.message
: 'Unknown close error',
});
}
}
return {
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
};
}
// Don't close - user needs to interact via Live View
}
async checkLoginStatus(
sessionId: string,
url: string,
): Promise<{ isLoggedIn: boolean; username?: string }> {
const stagehand = await this.createStagehand(sessionId);
try {
const page = await this.ensureActivePage(stagehand);
await page.goto(url, {
waitUntil: 'domcontentloaded',
timeoutMs: 30000,
});
await delay(1500);
// Use extract to check login status
const loginSchema = z.object({
isLoggedIn: z
.boolean()
.describe('Whether the user is currently logged in to this site'),
username: z.string().optional().describe('The username if logged in'),
});
const result = (await stagehand.extract(
'Check if the user is logged in to this website. Look for a user avatar, profile menu, or account dropdown in the header/navigation. If logged in, extract the username if visible.',
loginSchema as any,
)) as { isLoggedIn: boolean; username?: string };
return {
isLoggedIn: result.isLoggedIn,
username: result.username,
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const isNoPage =
message.includes('awaitActivePage') ||
message.includes('no page available') ||
message.includes('No page found');
if (isNoPage) {
throw new Error(
'Browser session ended before we could verify login status. Please retry.',
);
}
throw err;
} finally {
await this.safeCloseStagehand(stagehand);
}
}
// ===== Browser Automation CRUD =====
async createBrowserAutomation(data: {
taskId: string;
name: string;
description?: string;
targetUrl: string;
instruction: string;
schedule?: string;
}) {
return db.browserAutomation.create({
data: {
taskId: data.taskId,
name: data.name,
description: data.description,
targetUrl: data.targetUrl,
instruction: data.instruction,
schedule: data.schedule,
isEnabled: true, // Enable by default so scheduled runs work
},
});
}
async getBrowserAutomation(automationId: string) {
return db.browserAutomation.findUnique({
where: { id: automationId },
include: {
runs: {
orderBy: { createdAt: 'desc' },
take: 10,
},
},
});
}
async getBrowserAutomationsForTask(taskId: string) {
return db.browserAutomation.findMany({
where: { taskId },
include: {
runs: {
orderBy: { createdAt: 'desc' },
take: 1,
},
},
orderBy: { createdAt: 'desc' },
});
}
async updateBrowserAutomation(
automationId: string,
data: {
name?: string;
description?: string;
targetUrl?: string;
instruction?: string;
schedule?: string;
isEnabled?: boolean;
},
) {
return db.browserAutomation.update({
where: { id: automationId },
data,
});
}
async deleteBrowserAutomation(automationId: string) {
return db.browserAutomation.delete({
where: { id: automationId },
});
}
// ===== Browser Automation Execution =====
/**
* Start an automation run with a live session that the user can watch
*/
async startAutomationWithLiveView(
automationId: string,
organizationId: string,
): Promise<{
runId: string;
sessionId: string;
liveViewUrl: string;
error?: string;
needsReauth?: boolean;
}> {
const automation = await db.browserAutomation.findUnique({
where: { id: automationId },
});
if (!automation) {
throw new Error('Automation not found');
}
const context = await this.getOrgContext(organizationId);
if (!context) {
return {
runId: '',
sessionId: '',
liveViewUrl: '',
needsReauth: true,
error: 'No browser context found. Please connect your browser first.',
};
}
// Create a run record
const run = await db.browserAutomationRun.create({
data: {
automationId,
status: 'running',
startedAt: new Date(),
},
});
// Create session with live view
const { sessionId, liveViewUrl } = await this.createSessionWithContext(
context.contextId,
);
return {
runId: run.id,
sessionId,
liveViewUrl,
};
}
/**
* Execute an automation on an existing session (for live view runs)
*/
async executeAutomationOnSession(
automationId: string,
runId: string,
sessionId: string,
organizationId: string,
): Promise<{
success: boolean;
screenshotUrl?: string;
evaluationStatus?: 'pass' | 'fail';
evaluationReason?: string;
error?: string;
needsReauth?: boolean;
}> {
const automation = await db.browserAutomation.findUnique({
where: { id: automationId },
include: {
task: {
select: { title: true, description: true },
},
},
});
if (!automation) {
throw new Error('Automation not found');
}
const run = await db.browserAutomationRun.findUnique({
where: { id: runId },
});
if (!run) {
throw new Error('Run not found');
}
try {
const result = await this.executeAutomation(
sessionId,
automation.targetUrl,
automation.instruction,
{
title: automation.task.title,
description: automation.task.description,
},
);
if (!result.success) {
// Store evaluation data even on failure (requirement not met)
await db.browserAutomationRun.update({
where: { id: runId },
data: {
status: 'failed',
completedAt: new Date(),
durationMs: run.startedAt
? Date.now() - run.startedAt.getTime()
: 0,
error: result.error,
evaluationStatus: result.evaluationStatus,
evaluationReason: result.evaluationReason,
},
});
return {
success: false,
error: result.error,
evaluationStatus: result.evaluationStatus,
evaluationReason: result.evaluationReason,
needsReauth: result.needsReauth,
};
}
// Upload screenshot to S3 (only taken if evaluation passed)
let screenshotKey: string | undefined;
let presignedUrl: string | undefined;
if (result.screenshot) {
screenshotKey = await this.uploadScreenshot(
organizationId,
automationId,
runId,
result.screenshot,
);
presignedUrl = await this.getPresignedUrl(screenshotKey);
}
// Update run as completed
await db.browserAutomationRun.update({
where: { id: runId },
data: {
status: 'completed',
completedAt: new Date(),
durationMs: run.startedAt ? Date.now() - run.startedAt.getTime() : 0,
screenshotUrl: screenshotKey,
evaluationStatus: result.evaluationStatus ?? null,
evaluationReason: result.evaluationReason ?? 'Screenshot captured',
},
});
return {
success: true,
screenshotUrl: presignedUrl,
evaluationStatus: result.evaluationStatus,
evaluationReason: result.evaluationReason,
};
} catch (err) {
this.logger.error('Failed to execute automation on session', err);
await db.browserAutomationRun.update({
where: { id: runId },
data: {
status: 'failed',
completedAt: new Date(),
durationMs: run.startedAt ? Date.now() - run.startedAt.getTime() : 0,
error: err instanceof Error ? err.message : 'Unknown error',
},
});
return {
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
};
}
}
async runBrowserAutomation(
automationId: string,
organizationId: string,
): Promise<{
runId: string;
success: boolean;
screenshotUrl?: string;
evaluationStatus?: 'pass' | 'fail';
evaluationReason?: string;
error?: string;
needsReauth?: boolean;
}> {
// Get the automation with task context
const automation = await db.browserAutomation.findUnique({
where: { id: automationId },
include: {
task: {
select: { title: true, description: true },
},
},
});
if (!automation) {
throw new Error('Automation not found');
}
// Get org context
const context = await this.getOrgContext(organizationId);
if (!context) {
return {
runId: '',
success: false,
needsReauth: true,
error: 'No browser context found. Please connect your browser first.',
};
}
// Create a run record
const run = await db.browserAutomationRun.create({
data: {
automationId,
status: 'running',
startedAt: new Date(),
},
});
try {
// Create a session
const { sessionId } = await this.createSessionWithContext(
context.contextId,
);
try {
const result = await this.executeAutomation(
sessionId,
automation.targetUrl,
automation.instruction,
{
title: automation.task.title,
description: automation.task.description,
},
);
if (!result.success) {
// Update run as failed - include evaluation data if requirement not met
await db.browserAutomationRun.update({
where: { id: run.id },
data: {
status: 'failed',
completedAt: new Date(),
durationMs: Date.now() - run.startedAt!.getTime(),
error: result.error,
evaluationStatus: result.evaluationStatus,
evaluationReason: result.evaluationReason,
},
});
return {
runId: run.id,
success: false,
error: result.error,
evaluationStatus: result.evaluationStatus,
evaluationReason: result.evaluationReason,
needsReauth: result.needsReauth,
};
}
// Upload screenshot to S3 (only taken if evaluation passed)
let screenshotKey: string | undefined;
let presignedUrl: string | undefined;
if (result.screenshot) {
screenshotKey = await this.uploadScreenshot(
organizationId,
automationId,
run.id,
result.screenshot,
);
presignedUrl = await this.getPresignedUrl(screenshotKey);
}
// Update run as completed
await db.browserAutomationRun.update({
where: { id: run.id },
data: {
status: 'completed',
completedAt: new Date(),
durationMs: Date.now() - run.startedAt!.getTime(),
screenshotUrl: screenshotKey,
evaluationStatus: result.evaluationStatus ?? null,
evaluationReason: result.evaluationReason ?? 'Screenshot captured',
},
});
return {
runId: run.id,
success: true,
screenshotUrl: presignedUrl,
evaluationStatus: result.evaluationStatus,
evaluationReason: result.evaluationReason,
};
} finally {
// Always attempt to close the session, but never let cleanup override success
try {
await this.closeSession(sessionId);
} catch (err) {
this.logger.warn('Failed to close Browserbase session (ignored)', {
sessionId,
error: err instanceof Error ? err.message : String(err),
});
}
}
} catch (err) {
this.logger.error('Failed to run browser automation', err);
// Update run as failed
await db.browserAutomationRun.update({
where: { id: run.id },
data: {
status: 'failed',
completedAt: new Date(),
durationMs: run.startedAt ? Date.now() - run.startedAt.getTime() : 0,
error: err instanceof Error ? err.message : 'Unknown error',
},
});
return {
runId: run.id,
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
};
}
}
private async executeAutomation(
sessionId: string,
targetUrl: string,
instruction: string,
taskContext?: { title: string; description?: string | null },
): Promise<{
success: boolean;
screenshot?: string;
evaluationStatus?: 'pass' | 'fail';
evaluationReason?: string;
error?: string;
needsReauth?: boolean;
}> {
const stagehand = await this.createStagehand(sessionId);
try {
let page = await this.ensureActivePage(stagehand);
// Navigate to target URL
await page.goto(targetUrl, {
waitUntil: 'domcontentloaded',
timeoutMs: 30000,
});
await delay(1000);
// Check if we need to authenticate (look for login page indicators)
const loginSchema = z.object({
isLoggedIn: z.boolean(),
});
const authCheck = (await stagehand.extract(
'Check if the user is logged in to this website. Look for a user avatar, profile menu, account dropdown, or login/sign-in buttons. Return true if logged in, false if you see login buttons or a login form.',
loginSchema as any,
)) as { isLoggedIn: boolean };
if (!authCheck.isLoggedIn) {
return {
success: false,
needsReauth: true,
error: 'Session expired. Please re-authenticate in browser settings.',
};
}
// Execute the navigation instruction using Stagehand agent
const fullInstruction = `${instruction}. After completing all navigation steps, stop and wait.`;
await stagehand
.agent({
cua: true,
model: {
modelName: STAGEHAND_CUA_MODEL,
apiKey: process.env.ANTHROPIC_API_KEY,
},
})
.execute({
instruction: fullInstruction,
maxSteps: 20,
});
// Wait for final page to settle
await delay(2000);
// Always take a screenshot at the end (no pass/fail criteria gate)
page = await this.ensureActivePage(stagehand);
const screenshot = await page.screenshot({
type: 'jpeg',
quality: 80,
fullPage: false,
});
return {
success: true,
screenshot: screenshot.toString('base64'),
evaluationReason: taskContext
? `Navigation completed for "${taskContext.title}". Screenshot captured.`
: 'Navigation completed. Screenshot captured.',
};
} catch (err) {
this.logger.error('Failed to execute automation', err);
const message = err instanceof Error ? err.message : String(err);
const isNoPage =
message.includes('awaitActivePage') ||
message.includes('no page available') ||
message.includes('No page found');
return {
success: false,
needsReauth: isNoPage ? true : undefined,
error: isNoPage
? 'Browser session ended before we could capture evidence. Please retry.'
: message,
};
} finally {
await this.safeCloseStagehand(stagehand);
}
}
private async uploadScreenshot(
organizationId: string,
automationId: string,
runId: string,
base64Screenshot: string,
): Promise<string> {
const buffer = Buffer.from(base64Screenshot, 'base64');
const key = `browser-automations/${organizationId}/${automationId}/${runId}.jpg`;
await this.s3Client.send(
new PutObjectCommand({
Bucket: this.bucketName,
Key: key,
Body: buffer,
ContentType: 'image/jpeg',
}),
);
// Return just the key - we'll generate presigned URLs when viewing
return key;
}
async getPresignedUrl(key: string, expiresIn = 3600): Promise<string> {
const command = new GetObjectCommand({
Bucket: this.bucketName,
Key: key,
});
return getSignedUrl(this.s3Client, command, { expiresIn });
}
async getRunWithPresignedUrl(runId: string) {
const run = await db.browserAutomationRun.findUnique({
where: { id: runId },
});
if (!run) return null;
if (run.screenshotUrl) {
const presignedUrl = await this.getPresignedUrl(run.screenshotUrl);
return { ...run, screenshotUrl: presignedUrl };
}
return run;
}
async getAutomationsWithPresignedUrls(taskId: string) {
const automations = await this.getBrowserAutomationsForTask(taskId);
return Promise.all(
automations.map(async (automation) => {
const runsWithUrls = await Promise.all(
automation.runs.map(async (run) => {
if (run.screenshotUrl) {
const presignedUrl = await this.getPresignedUrl(
run.screenshotUrl,
);
return { ...run, screenshotUrl: presignedUrl };
}
return run;
}),
);
return { ...automation, runs: runsWithUrls };
}),
);
}
// ===== Run History =====
async getAutomationRuns(automationId: string, limit = 20) {
return db.browserAutomationRun.findMany({
where: { automationId },
orderBy: { createdAt: 'desc' },
take: limit,
});
}
async getAutomationRun(runId: string) {
return db.browserAutomationRun.findUnique({
where: { id: runId },
});
}
}