Open History to see the last commit
1import type {
2 ComputerDriver,
3 ComputerDriverFactory,
4 MouseButton,
5} from '@tanstack/ai-computer-use'
6import type { LaunchOptions } from 'playwright-core'
7
8type PageMouseButton = 'left' | 'right' | 'middle'
9
10/** The slice of a Playwright `Page` the driver uses. */
11export interface PlaywrightPageLike {
12 viewportSize: () => { width: number; height: number } | null
13 screenshot: (options: {
14 type: 'png'
15 clip?: { x: number; y: number; width: number; height: number }
16 }) => Promise<Uint8Array>
17 mouse: {
18 move: (x: number, y: number) => Promise<void>
19 down: (options: { button: PageMouseButton }) => Promise<void>
20 up: (options: { button: PageMouseButton }) => Promise<void>
21 click: (
22 x: number,
23 y: number,
24 options: { button: PageMouseButton; clickCount: number },
25 ) => Promise<void>
26 wheel: (deltaX: number, deltaY: number) => Promise<void>
27 }
28 keyboard: {
29 down: (key: string) => Promise<void>
30 up: (key: string) => Promise<void>
31 press: (key: string) => Promise<void>
32 type: (text: string) => Promise<void>
33 }
34 goBack: () => Promise<unknown>
35 goForward: () => Promise<unknown>
36 goto: (url: string) => Promise<unknown>
37}
38
39/** The slice of a Playwright `BrowserContext` the factory uses. */
40export interface PlaywrightContextLike {
41 newPage: () => Promise<PlaywrightPageLike>
42 close: () => Promise<void>
43}
44
45/** The slice of a Playwright `Browser` the factory uses. */
46export interface PlaywrightBrowserLike {
47 newContext: (options: {
48 viewport: { width: number; height: number }
49 }) => Promise<PlaywrightContextLike>
50 close: () => Promise<void>
51}
52
53export interface PlaywrightComputerDriverOptions {
54 /** The page to control. It must have a viewport size. */
55 page: PlaywrightPageLike
56}
57
58export interface PlaywrightComputerOptions {
59 /** The URL that each new page opens. Without it, the page stays blank. */
60 startUrl?: string
61 /** The viewport of each page in pixels. The default is 1280 x 800. */
62 display?: { width: number; height: number }
63 /**
64 * The browser that makes the pages. Without it, the factory launches
65 * Chromium on the first thread. A browser you pass in stays open.
66 */
67 browser?: PlaywrightBrowserLike
68 /** The options for `chromium.launch`. With `browser`, the factory ignores them. */
69 launch?: LaunchOptions
70}
71
72/**
73 * Create a computer driver that controls one Playwright page.
74 *
75 * The driver reads the viewport size once, at create. Key names go to
76 * Playwright as they are, because Playwright uses `KeyboardEvent.key` names.
77 *
78 * @example
79 * const driver = createPlaywrightComputerDriver({ page })
80 *
81 * @throws Error when the page has no viewport size.
82 */
83export function createPlaywrightComputerDriver({
84 page,
85}: PlaywrightComputerDriverOptions) {
86 const display = page.viewportSize()
87 if (display === null) {
88 throw new Error(
89 'The page has no viewport size. Set a viewport on the browser context.',
90 )
91 }
92
93 async function history(button: 'back' | 'forward') {
94 if (button === 'back') await page.goBack()
95 else await page.goForward()
96 }
97
98 const driver: ComputerDriver = {
99 display,
100 environment: 'browser',
101 screenshot: () => page.screenshot({ type: 'png' }),
102 async click(x, y, { button, count }) {
103 if (button === 'back' || button === 'forward') return history(button)
104 await page.mouse.click(x, y, { button, clickCount: count })
105 },
106 move: (x, y) => page.mouse.move(x, y),
107 async mouseDown(button: MouseButton) {
108 // ponytail: back and forward navigate once, on mouseUp. mouseDown does nothing for them.
109 if (button === 'back' || button === 'forward') return
110 await page.mouse.down({ button })
111 },
112 async mouseUp(button: MouseButton) {
113 if (button === 'back' || button === 'forward') return history(button)
114 await page.mouse.up({ button })
115 },
116 async scroll(x, y, deltaX, deltaY) {
117 await page.mouse.move(x, y)
118 await page.mouse.wheel(deltaX, deltaY)
119 },
120 keyDown: (key) => page.keyboard.down(key),
121 keyUp: (key) => page.keyboard.up(key),
122 press: (keys) => page.keyboard.press(keys.join('+')),
123 type: (text) => page.keyboard.type(text),
124 zoom: (region) => page.screenshot({ type: 'png', clip: region }),
125 navigate: async (url) => {
126 await page.goto(url)
127 },
128 }
129 return driver
130}
131
132/**
133 * Create a driver factory that gives each thread its own browser page.
134 *
135 * Each thread gets its own browser context, with its own cookies and
136 * storage. When the thread closes, its context closes. When you pass no
137 * `browser`, the factory launches Chromium once, on the first thread, and
138 * `close()` on the factory closes it.
139 *
140 * Without `browser`, the factory launches Chromium on the first thread.
141 * Install `playwright-core` and Chromium before that.
142 *
143 * @param options - The start URL, the display, and the browser or the launch options.
144 *
145 * @example
146 * const computer = createComputerUse({
147 * driver: playwrightComputer({ startUrl: 'https://tanstack.com' }),
148 * })
149 */
150export function playwrightComputer(options: PlaywrightComputerOptions = {}) {
151 const { startUrl, browser, launch } = options
152 const display = options.display ?? { width: 1280, height: 800 }
153 let launched: Promise<PlaywrightBrowserLike> | null = null
154
155 async function launchChromium() {
156 const { chromium } = await import('playwright-core')
157 return chromium.launch(launch)
158 }
159
160 function getBrowser() {
161 if (browser !== undefined) return Promise.resolve(browser)
162 launched ??= launchChromium().catch((error: unknown) => {
163 launched = null
164 throw error
165 })
166 return launched
167 }
168
169 const factory: ComputerDriverFactory = {
170 display,
171 environment: 'browser',
172 capabilities: { zoom: true, cursorPosition: false, navigate: true },
173 async create() {
174 const shared = await getBrowser()
175 const context = await shared.newContext({ viewport: display })
176 try {
177 const page = await context.newPage()
178 if (startUrl !== undefined) await page.goto(startUrl)
179 return {
180 ...createPlaywrightComputerDriver({ page }),
181 close: () => context.close(),
182 }
183 } catch (error) {
184 // Keep the page error. A failed close does not replace it.
185 await context.close().catch((closeError: unknown) => {
186 console.error(
187 'Failed to close the Playwright context after setup failed.',
188 closeError,
189 )
190 })
191 throw error
192 }
193 },
194 async close() {
195 const current = launched
196 launched = null
197 if (current === null) return
198 await (await current).close()
199 },
200 }
201 return factory
202}