Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified packages/sdk-go/internal/extensionassets/stagehand-extension.zip
Binary file not shown.
36 changes: 36 additions & 0 deletions packages/sdk-ts/tests/integration/timeouts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { z } from "zod/v4";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { ClientLLM, Stagehand } from "../../src/index.js";
import { closeStagehand, createStagehand, firstPage } from "./_support.js";

const hangingModel: ClientLLM = {
generate: () => new Promise<never>(() => {}),
};

describe("Stagehand operation timeouts", () => {
let stagehand: Stagehand;

beforeEach(async () => {
stagehand = await createStagehand({ model: hangingModel });
const page = await firstPage(stagehand);
await page.goto("data:text/html,<button>Continue</button><h1>Timeout fixture</h1>");
});

afterEach(async () => {
await closeStagehand(stagehand);
});

it("observe() enforces timeout", async () => {
await expect(stagehand.observe("find something", { timeout: 5 })).rejects.toThrow(/timed out/i);
}, 5_000);

it("extract() enforces timeout", async () => {
await expect(
stagehand.extract("Extract title", z.object({ title: z.string() }), { timeout: 5 }),
).rejects.toThrow(/timed out/i);
}, 5_000);

it("act() enforces timeout", async () => {
await expect(stagehand.act("click Continue", { timeout: 5 })).rejects.toThrow(/timed out/i);
}, 5_000);
});
77 changes: 45 additions & 32 deletions packages/server/controllers/stagehandController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import * as cacheService from "../services/cacheService.js";
import * as extractService from "../services/extractService.js";
import { buildGatewayContext } from "../llm/gatewayClient.js";
import * as observeService from "../services/observeService.js";
import { withTimeout } from "../timeoutConfig.js";

export type StagehandControllerOptions = {
initialize?: (params: StagehandInitParams) => Promise<StagehandInitResult>;
Expand Down Expand Up @@ -51,18 +52,22 @@ export function createStagehandController(
throw new Error("An LLM was not configured during Stagehand initialization");
}

const result = await actService.act({
params,
page: runtime.resolveUnderstudyPage(params.pageId),
model,
clientLLMGenerate: runtime.adapters.clientLLMGenerate,
logger,
systemPrompt: state.initParams.systemPrompt,
selfHeal: state.initParams.selfHeal,
domSettleTimeoutMs: state.initParams.domSettleTimeoutMs,
cache: cacheService.buildCacheContext(state.initParams),
gateway,
});
const result = await withTimeout(
actService.act({
params,
page: runtime.resolveUnderstudyPage(params.pageId),
model,
clientLLMGenerate: runtime.adapters.clientLLMGenerate,
logger,
systemPrompt: state.initParams.systemPrompt,
selfHeal: state.initParams.selfHeal,
domSettleTimeoutMs: state.initParams.domSettleTimeoutMs,
cache: cacheService.buildCacheContext(state.initParams),
gateway,
}),
params.options?.timeout,
"act()",
);
runtime.metrics.record("act", result.metadata.usage);
return result;
}
Expand All @@ -80,16 +85,20 @@ export function createStagehandController(
throw new Error("An LLM was not configured during Stagehand initialization");
}

const result = await observeService.observe({
params,
page: runtime.resolvePage(params.pageId),
model,
clientLLMGenerate: runtime.adapters.clientLLMGenerate,
logger,
systemPrompt: state.initParams.systemPrompt,
cache: cacheService.buildCacheContext(state.initParams),
gateway,
});
const result = await withTimeout(
observeService.observe({
params,
page: runtime.resolvePage(params.pageId),
model,
clientLLMGenerate: runtime.adapters.clientLLMGenerate,
logger,
systemPrompt: state.initParams.systemPrompt,
cache: cacheService.buildCacheContext(state.initParams),
gateway,
}),
params.options?.timeout,
"observe()",
);
runtime.metrics.record("observe", result.metadata.usage);
return result;
}
Expand All @@ -107,16 +116,20 @@ export function createStagehandController(
throw new Error("An LLM was not configured during Stagehand initialization");
}

const result = await extractService.extract({
params,
page: runtime.resolvePage(params.pageId),
model,
clientLLMGenerate: runtime.adapters.clientLLMGenerate,
logger,
systemPrompt: state.initParams.systemPrompt,
cache: cacheService.buildCacheContext(state.initParams),
gateway,
});
const result = await withTimeout(
extractService.extract({
params,
page: runtime.resolvePage(params.pageId),
model,
clientLLMGenerate: runtime.adapters.clientLLMGenerate,
logger,
systemPrompt: state.initParams.systemPrompt,
cache: cacheService.buildCacheContext(state.initParams),
gateway,
}),
params.options?.timeout,
"extract()",
);
runtime.metrics.record("extract", result.metadata.usage);
return result;
}
Expand Down
110 changes: 110 additions & 0 deletions packages/server/tests/stagehand-controller-timeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { StagehandInitParamsSchema, STAGEHAND_PROTOCOL_VERSION } from "../../protocol/schemas.js";
import { createStagehandController } from "../controllers/stagehandController.js";
import type { HandlerContext } from "../rpcRouter.js";
import { createStagehandRuntime } from "../runtime.js";
import * as actService from "../services/actService.js";
import * as extractService from "../services/extractService.js";
import * as observeService from "../services/observeService.js";
import { zeroStagehandResultUsage } from "../services/resultUsage.js";

const TIMEOUT_MS = 5;
type Operation = "act" | "observe" | "extract";

function createHarness() {
const runtime = createStagehandRuntime();
runtime.state.setState(
{
status: "initialized",
initParams: StagehandInitParamsSchema.parse({
protocolVersion: STAGEHAND_PROTOCOL_VERSION,
clientInfo: { name: "stagehand-controller-test", version: "1.0.0" },
model: { source: "client" },
logLevel: "off",
}),
},
true,
);
vi.spyOn(runtime, "resolvePage").mockReturnValue({} as never);
vi.spyOn(runtime, "resolveUnderstudyPage").mockReturnValue({} as never);
return {
controller: createStagehandController(runtime),
context: { logger: runtime.logger },
};
}

function callOperation(
controller: ReturnType<typeof createStagehandController>,
context: HandlerContext,
operation: Operation,
timeout?: number,
) {
const options = timeout === undefined ? undefined : { timeout };
switch (operation) {
case "act":
return controller.act(
{
pageId: "page-1",
instruction: "Click the button",
...(options ? { options } : {}),
},
context,
);
case "observe":
return controller.observe({ pageId: "page-1", ...(options ? { options } : {}) }, context);
case "extract":
return controller.extract(
{
pageId: "page-1",
instruction: "Extract the page",
schema: { type: "object" },
...(options ? { options } : {}),
},
context,
);
}
}

function mockOperation(operation: Operation, result: Promise<unknown>) {
switch (operation) {
case "act":
return vi.spyOn(actService, "act").mockReturnValue(result as never);
case "observe":
return vi.spyOn(observeService, "observe").mockReturnValue(result as never);
case "extract":
return vi.spyOn(extractService, "extract").mockReturnValue(result as never);
}
}

describe("Stagehand controller timeouts", () => {
afterEach(() => {
vi.restoreAllMocks();
});

it.each(["act", "observe", "extract"] as const)(
"applies the full-operation timeout to %s()",
async (operation) => {
const { controller, context } = createHarness();
const pending = new Promise<never>(() => {});
mockOperation(operation, pending);

await expect(callOperation(controller, context, operation, TIMEOUT_MS)).rejects.toThrow(
`${operation}() timed out after ${TIMEOUT_MS}ms`,
);
},
);

it.each(["act", "observe", "extract"] as const)(
"passes through a successful %s() when timeout is omitted",
async (operation) => {
const { controller, context } = createHarness();
const result = {
data: { operation },
metadata: { usage: zeroStagehandResultUsage() },
};
mockOperation(operation, Promise.resolve(result));

await expect(callOperation(controller, context, operation)).resolves.toBe(result);
},
);
});
5 changes: 5 additions & 0 deletions packages/server/timeoutConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { TimeoutError } from "./errors.js";

/**
* Enforce a caller-facing deadline. The supplied promise has no cancellation contract, so timing
* out does not abort underlying service or model work; callers that need cancellation must pass an
* abort signal through that operation's own API.
*/
export async function withTimeout<T>(
promise: Promise<T>,
timeout: number | null | undefined,
Expand Down
2 changes: 1 addition & 1 deletion scripts/test-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const integrationTestGroups = {
"local/page-navigation": ["page-addInitScript", "page-extra-http-headers", "page-goto-response"],
"local/page-interactions": ["click-count", "page-drag-and-drop", "page-hover", "page-scroll"],
"local/snapshots-ai": ["observe-element-id-format"],
"local/waits-timeouts": ["wait-for-selector", "wait-for-timeout"],
"local/waits-timeouts": ["timeouts", "wait-for-selector", "wait-for-timeout"],
} as const;

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
Expand Down
Loading