GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — opencode/packages/codemode/test/promise.test.ts at dev · Parad0X/opencode Expand file tree/ Copy pathpromise.test.tsMore file actions 1402 lines (1299 loc) · 45.9 KB / Copy pathpromise.test.tsFile metadata and controls1402 lines (1299 loc) · 45.9 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 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 import { describe, expect, test } from "bun:test" import { Deferred, Effect, Schema } from "effect" import { CodeMode, Tool, toolError } from "../src/index.js" // Wave 5 acceptance suite: first-class promise values. Un-awaited tool calls start eagerly on // supervised fibers, `await` settles them, Promise.all/allSettled/race/resolve/reject are // ordinary functions over arbitrary arrays mixing promises and plain values, and // .then/.catch/.finally chain reactions onto any promise. type Trace = { starts: Array<number> active: number maxActive: number completed: number interrupted: number } const makeTrace = (): Trace => ({ starts: [], active: 0, maxActive: 0, completed: 0, interrupted: 0 }) /** * Deterministic tool set: ordering and interruption are structural, never temporal. * * - `echo` settles immediately with its id. * - `gated` blocks until `open` releases the same id. Tool fibers start eagerly at the * call site, so several gated calls are provably live at once before any `open` runs. * - `pending` never settles; tests assert its interruption instead of racing a timer. * * Real clocks remain only in the wall-clock timeout tests (`timeoutMs`, `stubborn` * cleanup), where elapsed time is the behavior under test. */ const echoTool = (trace: Trace) => Tool.make({ description: "Echo an id immediately", input: Schema.Struct({ id: Schema.Number }), output: Schema.Number, execute: ({ id }) => Effect.sync(() => { trace.starts.push(id) trace.completed += 1 return id }), }) const gatedTool = (trace: Trace, gate: (id: number) => Deferred.Deferred<void>) => Tool.make({ description: "Echo an id once its gate opens", input: Schema.Struct({ id: Schema.Number }), output: Schema.Number, execute: ({ id }) => Effect.gen(function* () { trace.starts.push(id) trace.active += 1 trace.maxActive = Math.max(trace.maxActive, trace.active) yield* Deferred.await(gate(id)) trace.active -= 1 trace.completed += 1 return id }).pipe( Effect.onInterrupt(() => Effect.sync(() => { trace.active -= 1 trace.interrupted += 1 }), ), ), }) const openTool = (gate: (id: number) => Deferred.Deferred<void>) => Tool.make({ description: "Open the gate for an id", input: Schema.Struct({ id: Schema.Number }), output: Schema.Boolean, execute: ({ id }) => Deferred.succeed(gate(id), undefined), }) const pendingTool = (trace: Trace) => Tool.make({ description: "Never settle", input: Schema.Struct({ id: Schema.Number }), output: Schema.Number, execute: ({ id }) => Effect.gen(function* () { trace.starts.push(id) trace.active += 1 trace.maxActive = Math.max(trace.maxActive, trace.active) return yield* Effect.never }).pipe( Effect.onInterrupt(() => Effect.sync(() => { trace.active -= 1 trace.interrupted += 1 }), ), ), }) const failingTool = Tool.make({ description: "Always refuse", input: Schema.Struct({}), output: Schema.String, execute: () => Effect.fail(toolError("Lookup refused")), }) const interruptedTool = Tool.make({ description: "Interrupt this call", input: Schema.Struct({}), output: Schema.String, execute: () => Effect.interrupt, }) const completedTool = (trace: Trace) => Tool.make({ description: "Return the number of completed calls", input: Schema.Struct({}), output: Schema.Number, execute: () => Effect.succeed(trace.completed), }) /** Never settles, and holds interruption cleanup for `cleanupMs` so completion cleanup can outlast a timeout. */ const stubbornTool = (trace: Trace) => Tool.make({ description: "Never settle; clean up slowly when interrupted", input: Schema.Struct({ cleanupMs: Schema.Number }), output: Schema.Number, execute: ({ cleanupMs }) => Effect.never.pipe( Effect.onInterrupt(() => Effect.andThen( Effect.sleep(cleanupMs), Effect.sync(() => { trace.interrupted += 1 }), ), ), ), }) const run = ( code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}, ): Promise<CodeMode.Result> => { const trace = options.trace ?? makeTrace() const gates = new Map<number, Deferred.Deferred<void>>() const gate = (id: number): Deferred.Deferred<void> => { const existing = gates.get(id) if (existing) return existing const created = Deferred.makeUnsafe<void>() gates.set(id, created) return created } return Effect.runPromise( CodeMode.execute({ tools: { host: { echo: echoTool(trace), gated: gatedTool(trace, gate), open: openTool(gate), pending: pendingTool(trace), fail: failingTool, interrupt: interruptedTool, completed: completedTool(trace), stubborn: stubbornTool(trace), }, }, code, ...(options.limits ? { limits: options.limits } : {}), }), ) } const value = async (code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}) => { const result = await run(code, options) if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) return result.value } const error = async (code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}) => { const result = await run(code, options) if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) return result.error } describe("first-class promise values", () => { test("async functions return promises with isolated concurrent invocations", async () => { expect( await value(` const load = async (id) => { const result = await tools.host.echo({ id }) return [id, result] } const first = load(1) const second = load(2) return [first instanceof Promise, second instanceof Promise, await Promise.all([first, second])] `), ).toEqual([ true, true, [ [1, 1], [2, 2], ], ]) }) test("async function errors reject instead of throwing at the call site", async () => { expect( await value(` const fail = async () => { throw new Error("boom") } const promise = fail() try { await promise return "no" } catch (error) { return error.message } `), ).toBe("boom") }) test("an un-awaited tool call starts eagerly, in call order, before any await", async () => { const trace = makeTrace() const result = await value( ` const a = tools.host.gated({ id: 1 }) const b = tools.host.gated({ id: 2 }) await tools.host.open({ id: 1 }) await tools.host.open({ id: 2 }) const rb = await b const ra = await a return [ra, rb] `, { trace }, ) expect(result).toEqual([1, 2]) expect(trace.starts).toEqual([1, 2]) // Both calls overlapped even though they were awaited sequentially. expect(trace.maxActive).toBeGreaterThan(1) }) test("awaiting the same promise twice settles once and never re-runs the call", async () => { const result = await run(` const p = tools.host.echo({ id: 7 }) const x = await p const y = await p return [x, y] `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toEqual([7, 7]) expect(result.toolCalls).toStrictEqual([{ name: "host.echo" }]) }) test("await of a non-promise value passes it through unchanged", async () => { expect(await value(`return await 42`)).toBe(42) expect(await value(`const x = await "s"; return x`)).toBe("s") expect(await value(`return await null`)).toBeNull() expect(await value(`return (await [1, 2]).length`)).toBe(2) }) test("returning an un-awaited tool call resolves it (async-function return semantics)", async () => { expect(await value(`return tools.host.echo({ id: 9 })`)).toBe(9) }) test("typeof a promise is 'object', and console.log renders it sensibly", async () => { const result = await run(` const p = Promise.resolve(1) console.log(p) return typeof p `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("object") expect(result.logs).toStrictEqual(["[Promise (await it to get its value)]"]) }) test("an awaited failure is catchable exactly like a synchronous throw", async () => { const result = await run(` const p = tools.host.fail({}) try { await p return "no" } catch (e) { return e.message } `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("Lookup refused") expect(result.warnings).toBeUndefined() }) test("a fire-and-forget call is interrupted when the program returns", async () => { const trace = makeTrace() const result = await run( ` tools.host.pending({ id: 1 }) return "done" `, { trace }, ) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toBeUndefined() expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("a never-awaited failing call preserves the result and reports the rejection", async () => { const result = await run(` tools.host.fail({}) return "done" `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toStrictEqual([ { kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" }, ]) expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) }) test("a never-awaited failing async function is reported with a successful result", async () => { const result = await run(` const fail = async () => { throw new Error("boom") } fail() return "done" `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toStrictEqual([ { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: boom" }, ]) }) test("output truncation bounds warning diagnostics with an in-band marker", async () => { const result = await run( ` for (let i = 0; i < 100; i += 1) Promise.reject(new Error("x".repeat(1_000))) return "done" `, { limits: { maxOutputBytes: 64 } }, ) expect(result.ok).toBe(true) if (!result.ok) return expect(result.truncated).toBe(true) expect(result.warnings).toStrictEqual([ { kind: "Truncated", message: "100 additional warnings omitted by the output limit." }, ]) }) test("a budget-consuming value does not starve warnings", async () => { const result = await run( ` Promise.reject(new Error("boom")) return "x".repeat(500) `, { limits: { maxOutputBytes: 128 } }, ) expect(result.ok).toBe(true) if (!result.ok) return expect(result.truncated).toBe(true) expect(typeof result.value).toBe("string") expect(result.warnings).toStrictEqual([ { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: boom" }, ]) }) test("an un-awaited async function's pending chain is interrupted at the return", async () => { const trace = makeTrace() const result = await run( ` const run = async () => { await tools.host.pending({ id: 1 }) tools.host.fail({}) } run() return "done" `, { trace }, ) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toBeUndefined() expect(trace.starts).toEqual([1]) expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("reports every unhandled rejection in promise creation order", async () => { const result = await run(` Promise.reject(new Error("first")) tools.host.fail({}) Promise.reject(new Error("third")) return "done" `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.warnings).toStrictEqual([ { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: first" }, { kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" }, { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: third" }, ]) }) test("orders an async function rejection before promises created inside its body", async () => { const result = await run(` const outer = async () => { Promise.reject(new Error("inner")) throw new Error("outer") } outer() return "done" `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.warnings).toStrictEqual([ { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: outer" }, { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: inner" }, ]) }) test("un-awaited interruptions settle without becoming rejections", async () => { const result = await run(` tools.host.interrupt({}) Promise.all([tools.host.interrupt({})]) return "done" `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toBeUndefined() }) test("a fatal program error cancels outstanding work without reporting unhandled rejections", async () => { const trace = makeTrace() const result = await run( ` tools.host.pending({ id: 1 }) throw new Error("boom") `, { trace }, ) expect(result.ok).toBe(false) if (result.ok) return expect(result.error.message).toBe("Error: boom") expect("warnings" in result).toBe(false) expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("async-function promises remain owned by the execution after the function returns", async () => { const trace = makeTrace() expect( await value( ` const launch = async () => { tools.host.pending({ id: 1 }) Promise.all([tools.host.pending({ id: 2 })]) return "returned" } return await launch() `, { trace }, ), ).toBe("returned") // Both calls outlive launch() itself - they belong to the execution, not the function - // and are interrupted only when the whole program returns. expect(trace.starts).toEqual([1, 2]) expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(2) }) }) describe("promises at data boundaries", () => { test("an un-awaited promise inside a result or tool argument is awaited", async () => { expect(await value(`return { result: tools.host.echo({ id: 1 }) }`)).toEqual({ result: 1 }) expect(await value(`return Array.from([Promise.resolve(1)])`)).toEqual([1]) expect(await value(`return await tools.host.echo({ id: tools.host.echo({ id: 1 }) })`)).toBe(1) }) test("a rejected promise inside a result fails the program with its reason", async () => { const diagnostic = await error(`return { result: tools.host.fail({}) }`) expect(diagnostic.kind).toBe("ToolFailure") expect(diagnostic.message).toContain("Lookup refused") }) test("JSON.stringify of a promise is a diagnostic, not '{}'", async () => { const diagnostic = await error(`return JSON.stringify(Promise.resolve(1))`) expect(diagnostic.kind).toBe("InvalidDataValue") expect(diagnostic.message).toContain("un-awaited Promise") }) test("returning a never-settling promise inside data waits until the timeout", async () => { const trace = makeTrace() const result = await run( ` const pending = tools.host.pending({ id: 1 }) return { pending } `, { trace, limits: { timeoutMs: 100 } }, ) expect(result.ok).toBe(false) if (result.ok) return expect(result.error.kind).toBe("TimeoutExceeded") expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("operators reject promise operands", async () => { const diagnostic = await error(`return Promise.resolve(1) + 1`) expect(diagnostic.kind).toBe("InvalidDataValue") }) }) describe("Promise.all over arbitrary arrays", () => { test("combinators return promises that can be assigned and awaited later", async () => { expect( await value(` const all = Promise.all([Promise.resolve(1)]) const settled = Promise.allSettled([Promise.reject("no")]) const race = Promise.race([Promise.resolve(2)]) const promises = [all instanceof Promise, settled instanceof Promise, race instanceof Promise] return [promises, await all, await settled, await race] `), ).toEqual([[true, true, true], [1], [{ status: "rejected", reason: "no" }], 2]) }) test("separately-created aggregate batches overlap before either is awaited", async () => { const trace = makeTrace() expect( await value( ` const first = Promise.all([tools.host.gated({ id: 1 })]) const second = Promise.all([tools.host.gated({ id: 2 })]) await tools.host.open({ id: 1 }) await tools.host.open({ id: 2 }) return [await first, await second] `, { trace }, ), ).toEqual([[1], [2]]) expect(trace.starts).toEqual([1, 2]) expect(trace.maxActive).toBeGreaterThan(1) }) test("an aggregate created before a try block rejects at its later await", async () => { expect( await value(` const aggregate = Promise.all([tools.host.fail({})]) try { await aggregate return "no" } catch (error) { return error.message } `), ).toBe("Lookup refused") }) test("awaiting an aggregate repeatedly does not rerun its members", async () => { const result = await run(` const aggregate = Promise.all([tools.host.echo({ id: 7 })]) return [await aggregate, await aggregate] `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toEqual([[7], [7]]) expect(result.toolCalls).toStrictEqual([{ name: "host.echo" }]) }) test("mixes promises and plain values, preserving order", async () => { expect( await value(` return await Promise.all([tools.host.echo({ id: 1 }), "plain", tools.host.echo({ id: 2 }), 42]) `), ).toEqual([1, "plain", 2, 42]) }) test("accepts arrays built beforehand, passed as identifiers, and spread elements", async () => { expect( await value(` const calls = [] calls.push(tools.host.echo({ id: 1 })) calls.push(7) const more = [tools.host.echo({ id: 2 })] const batch = [...calls, ...more, "x"] return await Promise.all(batch) `), ).toEqual([1, 7, 2, "x"]) }) test("runs items.map tool calls in parallel", async () => { const trace = makeTrace() const result = await value( ` const ids = [1, 2, 3, 4] const calls = ids.map((id) => tools.host.gated({ id })) for (const id of ids) await tools.host.open({ id }) return await Promise.all(calls) `, { trace }, ) expect(result).toEqual([1, 2, 3, 4]) // maxActive counts truly-overlapping live executions, so > 1 proves real // parallelism deterministically - no wall-clock assertion needed. expect(trace.maxActive).toBeGreaterThan(1) }) test("runs async map callbacks concurrently", async () => { const trace = makeTrace() const result = await value( ` const ids = [1, 2, 3, 4] const calls = ids.map(async (id) => await tools.host.gated({ id })) for (const id of ids) await tools.host.open({ id }) return await Promise.all(calls) `, { trace }, ) expect(result).toEqual([1, 2, 3, 4]) expect(trace.maxActive).toBeGreaterThan(1) }) test("does not cap live tool-call concurrency", async () => { const trace = makeTrace() const result = await value( ` const ids = [] for (let i = 0; i < 20; i += 1) ids.push(i) const calls = ids.map((id) => tools.host.gated({ id })) for (const id of ids) await tools.host.open({ id }) const results = await Promise.all(calls) return results.length `, { trace }, ) expect(result).toBe(20) expect(trace.maxActive).toBe(20) }) test("resolves the empty array", async () => { expect(await value(`return await Promise.all([])`)).toEqual([]) }) test("rejects with the first failure, catchable in-program", async () => { const result = await run(` try { await Promise.all([tools.host.echo({ id: 1 }), tools.host.fail({})]) return "no" } catch (e) { return e.message } `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("Lookup refused") expect(result.warnings).toBeUndefined() }) test("rejects before an earlier slow promise fulfills", async () => { const trace = makeTrace() expect( await value( ` try { await Promise.all([ tools.host.pending({ id: 1 }), tools.host.fail({}), ]) return -1 } catch { return await tools.host.completed({}) } `, { trace }, ), ).toBe(0) // The surviving member is observed (Promise.all handled it), so completion interrupts // it instead of waiting for it. expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("fail-fast does not cancel a sibling the program still holds and awaits", async () => { const trace = makeTrace() expect( await value( ` const slow = tools.host.gated({ id: 1 }) try { await Promise.all([slow, tools.host.fail({})]) return "no" } catch {} await tools.host.open({ id: 1 }) return await slow `, { trace }, ), ).toBe(1) expect(trace.completed).toBe(1) expect(trace.interrupted).toBe(0) }) test("a slower observed sibling is interrupted at completion after failing fast", async () => { const trace = makeTrace() expect( await value( ` const failLater = async () => { await tools.host.pending({ id: 1 }) throw new Error("later") } const aggregate = Promise.all([Promise.reject(new Error("first")), failLater()]) try { await aggregate return "no" } catch (error) { return error.message } `, { trace }, ), ).toBe("first") expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("a non-collection argument is a clear error", async () => { const diagnostic = await error(`return await Promise.all(42)`) expect(diagnostic.message).toContain("Promise.all expects a synchronous iterable, received a number") }) test("exceeding maxToolCalls inside Promise.all is a ToolCallLimitExceeded diagnostic", async () => { const diagnostic = await error( `return await Promise.all([tools.host.echo({ id: 1 }), tools.host.echo({ id: 2 }), tools.host.echo({ id: 3 })])`, { limits: { maxToolCalls: 2 } }, ) expect(diagnostic.kind).toBe("ToolCallLimitExceeded") }) }) describe("Promise.allSettled", () => { test("reports fulfilled and rejected outcomes with catch-normalized reasons", async () => { expect( await value(` const settled = await Promise.allSettled([ tools.host.echo({ id: 5 }), tools.host.fail({}), "plain", Promise.reject(new Error("boom")), ]) return settled `), ).toEqual([ { status: "fulfilled", value: 5 }, { status: "rejected", reason: { name: "Error", message: "Lookup refused" } }, { status: "fulfilled", value: "plain" }, { status: "rejected", reason: { name: "Error", message: "boom" } }, ]) }) test("never rejects for program-level failures", async () => { const result = await run(` const settled = await Promise.allSettled([tools.host.fail({}), tools.host.fail({})]) return settled.filter((s) => s.status === "rejected").length `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe(2) expect(result.warnings).toBeUndefined() }) }) describe("Promise.race", () => { test("first settlement wins and a direct loser is interrupted at completion", async () => { const trace = makeTrace() const result = await value( ` const fast = tools.host.echo({ id: 1 }) const slow = tools.host.pending({ id: 2 }) return await Promise.race([fast, slow]) `, { trace }, ) expect(result).toBe(1) // The loser is observed (the race handled it), so the execution does not wait for it. expect(trace.completed).toBe(1) expect(trace.interrupted).toBe(1) }) test("a direct loser remains awaitable after the race settles", async () => { expect( await value(` const fast = tools.host.echo({ id: 1 }) const slow = tools.host.gated({ id: 2 }) const winner = await Promise.race([fast, slow]) await tools.host.open({ id: 2 }) return { winner, loser: await slow } `), ).toEqual({ winner: 1, loser: 2 }) }) test("a nested aggregate loser and its members are interrupted at completion", async () => { const trace = makeTrace() expect( await value( ` const nested = Promise.all([ tools.host.pending({ id: 1 }), tools.host.pending({ id: 2 }), ]) return await Promise.race(["immediate", nested]) `, { trace }, ), ).toBe("immediate") // The nested aggregate and its members are all observed, so nothing waits for them. expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(2) }) test("a rejection can win the race", async () => { expect( await value(` try { await Promise.race([tools.host.fail({}), tools.host.pending({ id: 1 })]) return "no" } catch (e) { return e.message } `), ).toBe("Lookup refused") }) test("a plain value wins over pending promises", async () => { const trace = makeTrace() expect(await value(`return await Promise.race([tools.host.pending({ id: 1 }), "immediate"])`, { trace })).toBe( "immediate", ) expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("a rejected race loser is observed by the aggregate", async () => { const result = await run(`return await Promise.race(["winner", tools.host.fail({})])`) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("winner") expect(result.warnings).toBeUndefined() }) test("an empty race is a clear error instead of hanging", async () => { const diagnostic = await error(`return await Promise.race([])`) expect(diagnostic.message).toContain("never settle") }) }) describe("Promise.resolve / Promise.reject", () => { test("resolve wraps plain values and passes promises through", async () => { expect(await value(`return await Promise.resolve(42)`)).toBe(42) expect(await value(`return await Promise.resolve(Promise.resolve("nested"))`)).toBe("nested") expect(await value(`return await Promise.resolve(tools.host.echo({ id: 3 }))`)).toBe(3) expect(await value(`const promise = Promise.resolve(1); return [promise].includes(Promise.resolve(promise))`)).toBe( true, ) }) test("reject produces a promise whose await throws the reason", async () => { expect( await value(` try { await Promise.reject("nope") return "no" } catch (e) { return e } `), ).toBe("nope") }) test("a rejection observed after settlement is handled", async () => { expect( await value(` const rejected = Promise.reject(new Error("handled")) await tools.host.echo({ id: 1 }) try { await rejected return "no" } catch (error) { return error.message } `), ).toBe("handled") }) test("an abandoned rejected promise is reported as unhandled", async () => { const result = await run(` Promise.reject(new Error("abandoned")) return "done" `) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toStrictEqual([ { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: abandoned" }, ]) }) }) describe("timeout interruption of forked calls", () => { test("the execution timeout interrupts in-flight forked fibers", async () => { const trace = makeTrace() const result = await run( ` const a = tools.host.pending({ id: 1 }) const b = tools.host.pending({ id: 2 }) return await a `, { trace, limits: { timeoutMs: 100 } }, ) expect(result.ok).toBe(false) if (result.ok) return expect(result.error.kind).toBe("TimeoutExceeded") // Both calls started; neither escaped the timeout - the awaited one AND the abandoned one. expect(trace.starts).toEqual([1, 2]) expect(trace.interrupted).toBe(2) expect(trace.completed).toBe(0) }) test("the timeout also interrupts calls inside Promise.all", async () => { const trace = makeTrace() const result = await run( `return await Promise.all([tools.host.pending({ id: 1 }), tools.host.pending({ id: 2 })])`, { trace, limits: { timeoutMs: 100 } }, ) expect(result.ok).toBe(false) if (result.ok) return expect(result.error.kind).toBe("TimeoutExceeded") expect(trace.interrupted).toBe(2) }) test("a non-settling race loser cannot hold the execution to the timeout", async () => { const trace = makeTrace() const result = await run(`return await Promise.race(["winner", tools.host.pending({ id: 1 })])`, { trace, limits: { timeoutMs: 100 }, }) // Completion interrupts the observed loser immediately; the race result survives. expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("winner") expect(result.warnings).toBeUndefined() expect(trace.starts).toEqual([1]) expect(trace.completed).toBe(0) expect(trace.interrupted).toBe(1) }) test("a timeout during completion cleanup keeps the computed value and warns", async () => { const trace = makeTrace() const result = await run( ` tools.host.stubborn({ cleanupMs: 400 }) return "done" `, { trace, limits: { timeoutMs: 100 } }, ) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toStrictEqual([ { kind: "TimeoutExceeded", message: "The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.", }, ]) expect(trace.interrupted).toBe(1) expect(trace.completed).toBe(0) }) test("a timeout during completion cleanup reports the timeout warning before settled rejections", async () => { const result = await run( ` tools.host.fail({}) tools.host.stubborn({ cleanupMs: 400 }) return "done" `, { limits: { timeoutMs: 100 } }, ) expect(result.ok).toBe(true) if (!result.ok) return expect(result.value).toBe("done") expect(result.warnings).toStrictEqual([ { kind: "TimeoutExceeded", message: "The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.", |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |