The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // Alchemy modifications are licensed under Apache-2.0. |
| 2 | // This file includes third-party code; see /THIRD_PARTY_LICENSES.md. |
| 3 | import type { |
| 4 | ModifierCallback, |
| 5 | WorkflowBinding, |
| 6 | WorkflowInstanceIntrospector, |
| 7 | WorkflowInstanceModifier, |
| 8 | WorkflowIntrospectionOperation, |
| 9 | WorkflowIntrospectionStreamResult, |
| 10 | WorkflowIntrospector, |
| 11 | WorkflowStepSelector, |
| 12 | } from "./types.ts"; |
| 13 | |
| 14 | function normalizeStreamMockChunk(value: unknown): Uint8Array { |
| 15 | if (value instanceof Uint8Array) { |
| 16 | return value; |
| 17 | } |
| 18 | |
| 19 | if (value instanceof ArrayBuffer) { |
| 20 | return new Uint8Array(value); |
| 21 | } |
| 22 | |
| 23 | if (ArrayBuffer.isView(value) && !(value instanceof DataView)) { |
| 24 | return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); |
| 25 | } |
| 26 | |
| 27 | throw new TypeError( |
| 28 | "Workflow mockStepResult() ReadableStream chunks must be ArrayBuffer or TypedArray values.", |
| 29 | ); |
| 30 | } |
| 31 | |
| 32 | async function readStreamMockChunks(stream: ReadableStream<unknown>): Promise<Array<Uint8Array>> { |
| 33 | if (stream.locked) { |
| 34 | throw new TypeError( |
| 35 | "Workflow mockStepResult() received a locked or unreadable ReadableStream.", |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | const chunks: Array<Uint8Array> = []; |
| 40 | const reader = stream.getReader(); |
| 41 | let fullyRead = false; |
| 42 | try { |
| 43 | while (true) { |
| 44 | const result = await reader.read(); |
| 45 | if (result.done) { |
| 46 | fullyRead = true; |
| 47 | return chunks; |
| 48 | } |
| 49 | |
| 50 | const chunk = normalizeStreamMockChunk(result.value); |
| 51 | if (chunk.byteLength === 0) { |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | chunks.push(chunk.slice()); |
| 56 | } |
| 57 | } finally { |
| 58 | if (!fullyRead) { |
| 59 | await reader.cancel("stream mock consumption stopped before completion").catch(() => {}); |
| 60 | } |
| 61 | try { |
| 62 | reader.releaseLock(); |
| 63 | } catch { |
| 64 | /** Reader may still be processing cancel(). */ |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | export class WorkflowInstanceModificationRecorder implements WorkflowInstanceModifier { |
| 70 | constructor(private readonly operations: Array<WorkflowIntrospectionOperation>) {} |
| 71 | |
| 72 | async disableSleeps(steps?: Array<WorkflowStepSelector>): Promise<void> { |
| 73 | this.operations.push({ type: "disableSleeps", steps }); |
| 74 | } |
| 75 | |
| 76 | async disableRetryDelays(steps?: Array<WorkflowStepSelector>): Promise<void> { |
| 77 | this.operations.push({ type: "disableRetryDelays", steps }); |
| 78 | } |
| 79 | |
| 80 | async mockStepResult(step: WorkflowStepSelector, stepResult: unknown): Promise<void> { |
| 81 | if (stepResult instanceof ReadableStream) { |
| 82 | const streamResult: WorkflowIntrospectionStreamResult = { |
| 83 | __workflowIntrospectionStreamResult: true, |
| 84 | chunks: await readStreamMockChunks(stepResult), |
| 85 | }; |
| 86 | this.operations.push({ |
| 87 | type: "mockStepResult", |
| 88 | step, |
| 89 | stepResult: streamResult, |
| 90 | }); |
| 91 | return; |
| 92 | } |
| 93 | |
| 94 | this.operations.push({ type: "mockStepResult", step, stepResult }); |
| 95 | } |
| 96 | |
| 97 | async mockStepError(step: WorkflowStepSelector, error: Error, times?: number): Promise<void> { |
| 98 | this.operations.push({ |
| 99 | type: "mockStepError", |
| 100 | step, |
| 101 | error: { name: error.name, message: error.message }, |
| 102 | times, |
| 103 | }); |
| 104 | } |
| 105 | |
| 106 | async forceStepTimeout(step: WorkflowStepSelector, times?: number): Promise<void> { |
| 107 | this.operations.push({ type: "forceStepTimeout", step, times }); |
| 108 | } |
| 109 | |
| 110 | async mockEvent(event: { type: string; payload: unknown }): Promise<void> { |
| 111 | this.operations.push({ type: "mockEvent", event }); |
| 112 | } |
| 113 | |
| 114 | async forceEventTimeout(step: WorkflowStepSelector): Promise<void> { |
| 115 | this.operations.push({ type: "forceEventTimeout", step }); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | export class WorkflowIntrospectorHandle implements WorkflowIntrospector { |
| 120 | #disposed = false; |
| 121 | #sessionId: string | undefined; |
| 122 | #instanceIntrospectors = new Map<string, WorkflowInstanceIntrospector>(); |
| 123 | #operations: Array<WorkflowIntrospectionOperation> = []; |
| 124 | |
| 125 | constructor(private readonly workflow: WorkflowBinding) {} |
| 126 | |
| 127 | async start(): Promise<void> { |
| 128 | this.#sessionId = await this.workflow.unsafeStartIntrospection(); |
| 129 | } |
| 130 | |
| 131 | private getSessionId(): string { |
| 132 | if (this.#sessionId === undefined) { |
| 133 | throw new Error("Workflow introspection has not started."); |
| 134 | } |
| 135 | return this.#sessionId; |
| 136 | } |
| 137 | |
| 138 | async modifyAll(fn: ModifierCallback): Promise<void> { |
| 139 | const sessionId = this.getSessionId(); |
| 140 | await fn(new WorkflowInstanceModificationRecorder(this.#operations)); |
| 141 | await this.workflow.unsafeSetIntrospectionOperations(sessionId, this.#operations); |
| 142 | } |
| 143 | |
| 144 | async get(): Promise<Array<WorkflowInstanceIntrospector>> { |
| 145 | const sessionId = this.getSessionId(); |
| 146 | await this.syncInstanceIntrospectors(sessionId); |
| 147 | |
| 148 | return Array.from(this.#instanceIntrospectors.values()); |
| 149 | } |
| 150 | |
| 151 | private async syncInstanceIntrospectors(sessionId: string): Promise<void> { |
| 152 | const instanceIds = await this.workflow.unsafeGetIntrospectionInstances(sessionId); |
| 153 | |
| 154 | for (const instanceId of instanceIds) { |
| 155 | if (!this.#instanceIntrospectors.has(instanceId)) { |
| 156 | this.#instanceIntrospectors.set( |
| 157 | instanceId, |
| 158 | new WorkflowInstanceIntrospectorHandle(this.workflow, instanceId), |
| 159 | ); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | private async stopIntrospectionSession(sessionId: string): Promise<void> { |
| 165 | try { |
| 166 | await this.syncInstanceIntrospectors(sessionId); |
| 167 | } finally { |
| 168 | await this.workflow.unsafeStopIntrospection(sessionId); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | private async disposeInstanceIntrospectors(): Promise<void> { |
| 173 | try { |
| 174 | await Promise.all( |
| 175 | Array.from(this.#instanceIntrospectors.values(), (introspector) => introspector.dispose()), |
| 176 | ); |
| 177 | } finally { |
| 178 | this.#instanceIntrospectors.clear(); |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | /** Keep this bound; explicit resource management may call the disposer unbound. */ |
| 183 | dispose = async (): Promise<void> => { |
| 184 | if (this.#disposed) { |
| 185 | return; |
| 186 | } |
| 187 | this.#disposed = true; |
| 188 | const sessionId = this.#sessionId; |
| 189 | |
| 190 | try { |
| 191 | if (sessionId !== undefined) { |
| 192 | await this.stopIntrospectionSession(sessionId); |
| 193 | } |
| 194 | } finally { |
| 195 | await this.disposeInstanceIntrospectors(); |
| 196 | } |
| 197 | }; |
| 198 | |
| 199 | async [Symbol.asyncDispose](): Promise<void> { |
| 200 | await this.dispose(); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | export class WorkflowInstanceIntrospectorHandle implements WorkflowInstanceIntrospector { |
| 205 | #disposed = false; |
| 206 | #instanceModifier: WorkflowInstanceModifier | undefined; |
| 207 | #instanceModifierPromise: Promise<WorkflowInstanceModifier> | undefined; |
| 208 | |
| 209 | constructor( |
| 210 | private readonly workflow: WorkflowBinding, |
| 211 | private readonly instanceId: string, |
| 212 | ) { |
| 213 | this.#instanceModifierPromise = workflow |
| 214 | .unsafeGetInstanceModifier(instanceId) |
| 215 | .then((modifier) => { |
| 216 | this.#instanceModifier = modifier as WorkflowInstanceModifier; |
| 217 | this.#instanceModifierPromise = undefined; |
| 218 | return this.#instanceModifier; |
| 219 | }); |
| 220 | |
| 221 | // To avoid an unhandled rejection when the handle is used without modify() |
| 222 | void this.#instanceModifierPromise.catch(() => {}); |
| 223 | } |
| 224 | |
| 225 | async modify(fn: ModifierCallback): Promise<WorkflowInstanceIntrospector> { |
| 226 | if (this.#instanceModifierPromise !== undefined) { |
| 227 | this.#instanceModifier = await this.#instanceModifierPromise; |
| 228 | } |
| 229 | if (this.#instanceModifier === undefined) { |
| 230 | throw new Error( |
| 231 | "could not apply modifications due to internal error. Retrying the test may resolve the issue.", |
| 232 | ); |
| 233 | } |
| 234 | |
| 235 | await fn(this.#instanceModifier); |
| 236 | |
| 237 | return this; |
| 238 | } |
| 239 | |
| 240 | async waitForStepResult(step: WorkflowStepSelector): Promise<unknown> { |
| 241 | return await this.workflow.unsafeWaitForStepResult(this.instanceId, step.name, step.index); |
| 242 | } |
| 243 | |
| 244 | async waitForStatus(status: string): Promise<void> { |
| 245 | if (status === "queued") { |
| 246 | return; |
| 247 | } |
| 248 | |
| 249 | await this.workflow.unsafeWaitForStatus(this.instanceId, status); |
| 250 | } |
| 251 | |
| 252 | async getOutput(): Promise<unknown> { |
| 253 | return await this.workflow.unsafeGetOutputOrError(this.instanceId, true); |
| 254 | } |
| 255 | |
| 256 | async getError(): Promise<{ name: string; message: string }> { |
| 257 | return (await this.workflow.unsafeGetOutputOrError(this.instanceId, false)) as { |
| 258 | name: string; |
| 259 | message: string; |
| 260 | }; |
| 261 | } |
| 262 | |
| 263 | /** Keep this bound; explicit resource management may call the disposer unbound. */ |
| 264 | dispose = async (): Promise<void> => { |
| 265 | if (this.#disposed) { |
| 266 | return; |
| 267 | } |
| 268 | this.#disposed = true; |
| 269 | try { |
| 270 | // Acquisition starts in the constructor, even if modify() is never called. |
| 271 | // If it failed, there is no modifier to dispose; modify() still reports it. |
| 272 | const modifier = |
| 273 | this.#instanceModifier ?? (await this.#instanceModifierPromise?.catch(() => undefined)); |
| 274 | (modifier as Partial<Disposable> | undefined)?.[Symbol.dispose]?.(); |
| 275 | } finally { |
| 276 | await this.workflow.unsafeAbort(this.instanceId, "Instance dispose"); |
| 277 | } |
| 278 | }; |
| 279 | |
| 280 | async [Symbol.asyncDispose](): Promise<void> { |
| 281 | await this.dispose(); |
| 282 | } |
| 283 | } |