@powerhousedao/switchboard 6.2.3-dev.84 → 6.2.3-dev.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.tsbuild/test/ai-gateway.test.d.ts +2 -0
  2. package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
  3. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  4. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  5. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  6. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  7. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts +2 -0
  8. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
  9. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
  10. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts.map +1 -0
  11. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  12. package/CHANGELOG.md +33 -0
  13. package/README.md +33 -0
  14. package/dist/boot.d.mts +1 -1
  15. package/dist/boot.mjs +1 -1
  16. package/dist/config/from-env.d.mts +1 -1
  17. package/dist/config/from-env.d.mts.map +1 -1
  18. package/dist/config/from-env.mjs +3 -3
  19. package/dist/config/schema.d.mts +1 -1
  20. package/dist/config/schema.mjs +3 -3
  21. package/dist/{from-env-BO0n9R02.mjs → from-env-BgyZQAxw.mjs} +79 -7
  22. package/dist/from-env-BgyZQAxw.mjs.map +1 -0
  23. package/dist/index.mjs +13 -10
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{plugin-host-C1sYEm8g.d.mts → plugin-host-C0bSz1Oe.d.mts} +2 -2
  26. package/dist/{plugin-host-C1sYEm8g.d.mts.map → plugin-host-C0bSz1Oe.d.mts.map} +1 -1
  27. package/dist/plugins/ai.d.mts +37 -0
  28. package/dist/plugins/ai.d.mts.map +1 -0
  29. package/dist/plugins/ai.mjs +352 -0
  30. package/dist/plugins/ai.mjs.map +1 -0
  31. package/dist/plugins/attachments.d.mts +1 -1
  32. package/dist/plugins/attachments.mjs +3 -3
  33. package/dist/plugins/mcp.d.mts +1 -1
  34. package/dist/plugins/privacy.d.mts +1 -1
  35. package/dist/plugins/workflows.d.mts +2 -2
  36. package/dist/plugins/workflows.mjs +3 -3
  37. package/dist/{schema-ivUWPQOn.d.mts → schema-DhempFjb.d.mts} +41 -1
  38. package/dist/schema-DhempFjb.d.mts.map +1 -0
  39. package/dist/{schema-0g_QdOWn.mjs → schema-XEZrdmag.mjs} +55 -6
  40. package/dist/schema-XEZrdmag.mjs.map +1 -0
  41. package/dist/{server-B3qhPKNn.mjs → server-BRVMofWD.mjs} +102 -14
  42. package/dist/server-BRVMofWD.mjs.map +1 -0
  43. package/dist/server.d.mts +7 -3
  44. package/dist/server.d.mts.map +1 -1
  45. package/dist/server.mjs +5 -5
  46. package/dist/{workflow-runtime-7GaJ13c9.d.mts → workflow-runtime-CF5pc8mt.d.mts} +5 -2
  47. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  48. package/dist/{workflows-B1VsL5Lo.mjs → workflows-C_pWcP2u.mjs} +446 -9
  49. package/dist/workflows-C_pWcP2u.mjs.map +1 -0
  50. package/package.json +22 -16
  51. package/test/ai-gateway.test.ts +555 -0
  52. package/test/config-from-env.test.ts +184 -0
  53. package/test/config-schema.test.ts +28 -0
  54. package/test/goldens/packages.graphql +1 -1
  55. package/test/goldens/privacy.graphql +1 -1
  56. package/test/goldens/reactor-drive-nodes.graphql +1 -1
  57. package/test/goldens/resolvers.json +4 -0
  58. package/test/goldens/supergraph.graphql +217 -1
  59. package/test/goldens/workflow-runtime.graphql +95 -1
  60. package/test/keyframe-reclaim-store.test.ts +156 -0
  61. package/test/processor-timing-log.test.ts +109 -0
  62. package/test/redact-webhook-path.test.ts +9 -0
  63. package/test/workflow/resolvers.test.ts +106 -0
  64. package/test/workflow/waitpoint-routes.test.ts +284 -0
  65. package/test/workflow/waitpoint-runtime.test.ts +204 -0
  66. package/tsdown.config.ts +1 -0
  67. package/dist/from-env-BO0n9R02.mjs.map +0 -1
  68. package/dist/schema-0g_QdOWn.mjs.map +0 -1
  69. package/dist/schema-ivUWPQOn.d.mts.map +0 -1
  70. package/dist/server-B3qhPKNn.mjs.map +0 -1
  71. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +0 -1
  72. package/dist/workflows-B1VsL5Lo.mjs.map +0 -1
@@ -28,6 +28,27 @@ scalar Amount_Percentage
28
28
 
29
29
  scalar Amount_Tokens
30
30
 
31
+ """
32
+ Who may decide an approval, and how the editor renders it.
33
+ """
34
+ type ApprovalRequest {
35
+ title: String!
36
+ """
37
+ Markdown.
38
+ """
39
+ body: String
40
+ approveLabel: String!
41
+ rejectLabel: String!
42
+ """
43
+ none | reject | both
44
+ """
45
+ reasonRequiredOn: String!
46
+ """
47
+ DIDs allowed to decide; empty means anyone with write access.
48
+ """
49
+ approvers: [String!]!
50
+ }
51
+
31
52
  scalar AttachmentRef
32
53
 
33
54
  """
@@ -687,6 +708,47 @@ scalar Unknown
687
708
 
688
709
  scalar Upload
689
710
 
711
+ """
712
+ A point where a run paused, and how it resumes.
713
+ """
714
+ type WaitpointRecord {
715
+ id: String!
716
+ runId: String!
717
+ workflowId: String!
718
+ stepId: String!
719
+ stepKey: String!
720
+ stepPath: String!
721
+ pieceName: String!
722
+ blockName: String!
723
+ """
724
+ DELAY | WEBHOOK
725
+ """
726
+ type: String!
727
+ """
728
+ approval | webhook | delay
729
+ """
730
+ kind: String!
731
+ """
732
+ PENDING | COMPLETED | CONSUMED | EXPIRED | CANCELLED
733
+ """
734
+ status: String!
735
+ createdAt: String!
736
+ """
737
+ DELAY only: when the run resumes.
738
+ """
739
+ resumeAt: String
740
+ expiresAt: String
741
+ resolvedAt: String
742
+ """
743
+ The DID that resolved it from the editor.
744
+ """
745
+ decidedBy: String
746
+ """
747
+ Set by the Request approval block; null otherwise.
748
+ """
749
+ approval: ApprovalRequest
750
+ }
751
+
690
752
  type WebhookEndpointRecord {
691
753
  workflowId: String!
692
754
  url: String!
@@ -731,6 +793,10 @@ type WorkflowRunRecord {
731
793
  workflowVersion: Int!
732
794
  triggerKind: String!
733
795
  triggerPayload: Unknown
796
+ """
797
+ PENDING | RUNNING | WAITING | SUCCEEDED | FAILED | CANCELLED. WAITING: paused
798
+ at a waitpoint (approval, webhook or delay); the run holds no worker.
799
+ """
734
800
  status: String!
735
801
  error: String
736
802
  errorName: String
@@ -749,6 +815,10 @@ type WorkflowRunRecord {
749
815
  """
750
816
  warningNotes: [String!]!
751
817
  steps: [WorkflowStepRunRecord!]!
818
+ """
819
+ Where the run paused, resolved ones included.
820
+ """
821
+ waitpoints: [WaitpointRecord!]!
752
822
  }
753
823
 
754
824
  type WorkflowRunResultPage {
@@ -822,6 +892,21 @@ type WorkflowRuntimeMutations {
822
892
  """
823
893
  rerun(runId: String!): WorkflowRunPayload!
824
894
  """
895
+ Approves or rejects a PENDING WEBHOOK waitpoint, resuming its run. Needs
896
+ write access to the workflow; with approvers listed, the caller's DID must
897
+ be one. reason may be required, per approval.reasonRequiredOn.
898
+ """
899
+ resolveWaitpoint(
900
+ waitpointId: String!
901
+ approved: Boolean!
902
+ reason: String
903
+ ): WaitpointRecord!
904
+ """
905
+ Cancels a WAITING or PENDING run and its open waitpoints. A RUNNING run
906
+ cannot be cancelled yet.
907
+ """
908
+ cancelRun(runId: String!): WorkflowRunPayload
909
+ """
825
910
  Mints a managed secret for a connection or workflow document and returns
826
911
  its ref; only that document resolves it. The value is stored encrypted
827
912
  and is never readable back over any API.
@@ -915,6 +1000,15 @@ type WorkflowRuntimeQueries {
915
1000
  ): WorkflowRunResultPage!
916
1001
  run(id: String!): WorkflowRunRecord
917
1002
  """
1003
+ WAITING runs, each with its waitpoints. Scope them to one
1004
+ workflow, or to every workflow a drive holds; workflowId wins.
1005
+ """
1006
+ waitingRuns(
1007
+ driveId: String
1008
+ workflowId: String
1009
+ first: Int
1010
+ ): [WorkflowRunRecord!]!
1011
+ """
918
1012
  The descriptor (props, auth, ports) of one action or trigger, as the
919
1013
  version that runs it describes it; triggers come back under "trigger".
920
1014
  """
@@ -1307,7 +1401,7 @@ type Workflow_WorkflowPolicy {
1307
1401
  """
1308
1402
  runTimeoutSeconds: Int!
1309
1403
  """
1310
- NOT YET ENFORCED. Bounds how long a run may stay suspended on a waitpoint - but nothing suspends: waitpoints, run.pause and generateResumeUrl all throw, so there is no suspended state to bound.
1404
+ Bounds how long a run may stay suspended on a waitpoint: a waitpoint expires this long after it is created, ending the run CANCELLED with WaitpointExpired. A Delay longer than this is refused.
1311
1405
  """
1312
1406
  maxSuspensionDays: Int!
1313
1407
  """
@@ -0,0 +1,156 @@
1
+ import {
2
+ EventBus,
3
+ ReactorBuilder,
4
+ type InProcessReactorModule,
5
+ } from "@powerhousedao/reactor";
6
+ import { documentModelDocumentModelModule } from "document-model";
7
+ import type { ILogger } from "document-model";
8
+ import { mkdtemp, rm } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { afterEach, describe, expect, it, vi } from "vitest";
12
+ import { createReactorKysely, resolveKeyframes } from "../src/server.mjs";
13
+
14
+ const LONG = 180_000;
15
+
16
+ function stubLogger(): ILogger {
17
+ const logger = {
18
+ level: "info",
19
+ verbose: () => undefined,
20
+ debug: () => undefined,
21
+ info: () => undefined,
22
+ warn: () => undefined,
23
+ error: () => undefined,
24
+ errorHandler: () => undefined,
25
+ child: () => logger,
26
+ };
27
+ return logger as unknown as ILogger;
28
+ }
29
+
30
+ function emptyDocument() {
31
+ return documentModelDocumentModelModule.utils.createDocument();
32
+ }
33
+
34
+ describe("resolveKeyframes", () => {
35
+ const CONFIG = "/project/powerhouse.config.json";
36
+
37
+ it("is unset with neither source, which keeps today's behaviour", () => {
38
+ expect(resolveKeyframes(undefined, undefined, CONFIG)).toBeUndefined();
39
+ });
40
+
41
+ it("reads the project config", () => {
42
+ expect(
43
+ resolveKeyframes(undefined, { default: { keep: 4 } }, CONFIG),
44
+ ).toEqual({ default: { keep: 4 } });
45
+ });
46
+
47
+ it("lets the configured rules win whole over the project config", () => {
48
+ expect(
49
+ resolveKeyframes(
50
+ { default: { keep: 1 } },
51
+ { default: { interval: 50 }, types: { "a/b": { keep: 9 } } },
52
+ CONFIG,
53
+ ),
54
+ ).toEqual({ default: { keep: 1 } });
55
+ });
56
+
57
+ it("stops the boot on a project config it cannot use, naming the file", () => {
58
+ expect(() =>
59
+ resolveKeyframes(undefined, { default: { keep: 0 } }, CONFIG),
60
+ ).toThrow(`${CONFIG} reactor.keyframes.default.keep`);
61
+ });
62
+ });
63
+
64
+ describe("keyframe clean-up and reclaim on a reactor's own store", () => {
65
+ let dataDir: string | undefined;
66
+ let module: InProcessReactorModule | undefined;
67
+
68
+ afterEach(async () => {
69
+ await module?.shutdown();
70
+ module = undefined;
71
+ if (dataDir) {
72
+ await rm(dataDir, { recursive: true, force: true, maxRetries: 5 });
73
+ }
74
+ dataDir = undefined;
75
+ });
76
+
77
+ it.each([
78
+ ["in a worker thread", true],
79
+ ["in the main thread", false],
80
+ ])(
81
+ "shrinks the table %s, after a dry run that left it alone",
82
+ async (_where, pgliteWorkers) => {
83
+ dataDir = await mkdtemp(join(tmpdir(), "ph-keyframe-reclaim-"));
84
+ const storage = await createReactorKysely({
85
+ reactorDbUrl: undefined,
86
+ reactorPgliteDir: join(dataDir, "reactor"),
87
+ reactorPgliteMajor: 17,
88
+ inMemory: false,
89
+ hostPoolSize: () => 1,
90
+ pgliteWorkers,
91
+ logger: stubLogger(),
92
+ });
93
+ expect(storage.storeMaintenance).toBeDefined();
94
+
95
+ module = await new ReactorBuilder()
96
+ .withEventBus(new EventBus())
97
+ .withKysely(storage.kysely)
98
+ .withKeyframes({ default: { keep: 1 } })
99
+ .withStoreMaintenance(storage.storeMaintenance!)
100
+ .buildModule();
101
+ const { keyframeCleanup, keyframeStore } = module;
102
+
103
+ const padded = emptyDocument();
104
+ const large = {
105
+ ...padded,
106
+ state: { ...padded.state, padding: "x".repeat(200_000) },
107
+ };
108
+ for (let revision = 10; revision <= 100; revision += 10) {
109
+ await keyframeStore.putKeyframe(
110
+ "doc",
111
+ "global",
112
+ "main",
113
+ revision,
114
+ large,
115
+ );
116
+ }
117
+
118
+ keyframeCleanup.start({ dryRun: true });
119
+ await vi.waitFor(
120
+ () => expect(keyframeCleanup.status()?.state).toBe("done"),
121
+ { timeout: 30_000 },
122
+ );
123
+ expect(keyframeCleanup.status()?.totals.removableRows).toBe(9);
124
+ expect(await keyframeStore.listKeyframes("doc")).toHaveLength(10);
125
+
126
+ keyframeCleanup.start({ dryRun: false });
127
+ await vi.waitFor(
128
+ () => expect(keyframeCleanup.status()?.state).toBe("done"),
129
+ { timeout: 30_000 },
130
+ );
131
+ const kept = await keyframeStore.listKeyframes("doc");
132
+ expect(kept.map((row) => row.revision)).toEqual([100]);
133
+
134
+ await keyframeCleanup.reclaim();
135
+ await vi.waitFor(
136
+ () =>
137
+ expect(keyframeCleanup.reclaimStatus()?.state).not.toBe("running"),
138
+ { timeout: 120_000, interval: 100 },
139
+ );
140
+
141
+ const reclaim = keyframeCleanup.reclaimStatus()!;
142
+ expect(reclaim.message).toBe("The Keyframe table was rewritten.");
143
+ expect(reclaim.state).toBe("done");
144
+ expect(reclaim.tableBytesAfter).toBeLessThan(reclaim.tableBytesBefore!);
145
+
146
+ const after = await keyframeStore.findNearestKeyframe(
147
+ "doc",
148
+ "global",
149
+ "main",
150
+ 100,
151
+ );
152
+ expect(after?.revision).toBe(100);
153
+ },
154
+ LONG,
155
+ );
156
+ });
@@ -0,0 +1,109 @@
1
+ import type { InspectorProcessorTimingReport } from "@powerhousedao/reactor";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { startProcessorTimingLog } from "../src/processor-timing-log.mjs";
4
+
5
+ function report(
6
+ level: InspectorProcessorTimingReport["level"],
7
+ phase: "catching-up" | "live",
8
+ ): InspectorProcessorTimingReport {
9
+ const counters = {
10
+ batches: 1,
11
+ opsDelivered: 1,
12
+ opsScanned: 1,
13
+ opsMatched: 1,
14
+ pages: 1,
15
+ handlerMs: 2_000,
16
+ maxBatchMs: 0,
17
+ readMs: 0,
18
+ lookupMs: 0,
19
+ fillMs: 0,
20
+ slotWaitMs: 0,
21
+ pauseMs: 0,
22
+ errors: 0,
23
+ };
24
+ const horizon = {
25
+ live: { ...counters, handlerMs: 0 },
26
+ replay: counters,
27
+ ordinalsAdvanced: 1,
28
+ busyMs: 2_000,
29
+ };
30
+ return {
31
+ level,
32
+ windowMs: 60_000,
33
+ head: 10,
34
+ headKnown: true,
35
+ processors: [
36
+ {
37
+ processorId: "p",
38
+ name: "Index",
39
+ driveLabel: "files",
40
+ factoryId: "f",
41
+ driveId: "d",
42
+ phase,
43
+ lastOrdinal: 5,
44
+ queueDepth: { tasks: 0, ops: 0 },
45
+ ordinalsBehind: 5,
46
+ opsPerSecond: 1,
47
+ ordinalsPerSecond: 1,
48
+ etaMs: null,
49
+ sinceUtcMs: 0,
50
+ total: horizon,
51
+ window: horizon,
52
+ windowMs: 60_000,
53
+ currentRun: null,
54
+ lastRun: null,
55
+ lastBatch: null,
56
+ byDocumentType: [],
57
+ },
58
+ ],
59
+ };
60
+ }
61
+
62
+ describe("startProcessorTimingLog", () => {
63
+ beforeEach(() => {
64
+ vi.useFakeTimers();
65
+ });
66
+
67
+ afterEach(() => {
68
+ vi.useRealTimers();
69
+ });
70
+
71
+ it("logs while catching up and one summary when it ends", () => {
72
+ let current = report("basic", "catching-up");
73
+ const lines: string[] = [];
74
+ const stop = startProcessorTimingLog({
75
+ intervalMs: 1_000,
76
+ read: () => current,
77
+ log: (line) => lines.push(line),
78
+ });
79
+
80
+ vi.advanceTimersByTime(2_000);
81
+ expect(lines).toHaveLength(2);
82
+ expect(lines[0]).toContain("catch-up slowest (60 s): Index·files 2.0s");
83
+
84
+ current = report("basic", "live");
85
+ vi.advanceTimersByTime(3_000);
86
+ expect(lines).toHaveLength(3);
87
+ expect(lines[2]).toMatch(/^catch-up done in .*Index·files 2\.0s$/);
88
+ stop();
89
+ });
90
+
91
+ it("stays quiet when live, when off, and after the stop", () => {
92
+ let current = report("basic", "live");
93
+ const log = vi.fn();
94
+ const stop = startProcessorTimingLog({
95
+ intervalMs: 1_000,
96
+ read: () => current,
97
+ log,
98
+ });
99
+ vi.advanceTimersByTime(2_000);
100
+
101
+ current = report("off", "catching-up");
102
+ vi.advanceTimersByTime(2_000);
103
+ stop();
104
+
105
+ current = report("basic", "catching-up");
106
+ vi.advanceTimersByTime(2_000);
107
+ expect(log).not.toHaveBeenCalled();
108
+ });
109
+ });
@@ -24,11 +24,20 @@ describe("redactWebhookPath", () => {
24
24
  );
25
25
  });
26
26
 
27
+ it("redacts a waitpoint's resume token and its sub-path", () => {
28
+ expect(
29
+ redactWebhookPath(
30
+ `/api/@powerhousedao/workflow/waitpoints/${TOKEN}/confirm?action=approve`,
31
+ ),
32
+ ).toBe("/api/@powerhousedao/workflow/waitpoints/[redacted]");
33
+ });
34
+
27
35
  it("never returns anything containing the token", () => {
28
36
  for (const url of [
29
37
  `/webhooks/${TOKEN}`,
30
38
  `/reactor/webhooks/${TOKEN}`,
31
39
  `/a/b/c/webhooks/${TOKEN}?x=1`,
40
+ `/a/waitpoints/${TOKEN}/sync`,
32
41
  ]) {
33
42
  expect(redactWebhookPath(url)).not.toContain(TOKEN);
34
43
  }
@@ -34,6 +34,41 @@ function runsInfo(query: string) {
34
34
  const emptyPage = (): Promise<unknown> =>
35
35
  Promise.resolve({ records: [], hasNextPage: false, cursor: null });
36
36
 
37
+ function waitpointRow(id: string, runId: string) {
38
+ return {
39
+ id,
40
+ run_id: runId,
41
+ workflow_id: "wf-1",
42
+ step_id: "step-1",
43
+ step_key: "step_1",
44
+ step_path: "step-1",
45
+ piece_name: "@powerhousedao/piece-approval",
46
+ block_name: "approval",
47
+ type: "WEBHOOK",
48
+ kind: "approval",
49
+ status: "PENDING",
50
+ created_at: "2026-10-28T00:00:00.000Z",
51
+ resume_at: null,
52
+ expires_at: null,
53
+ resolved_at: null,
54
+ decided_by: null,
55
+ approval: '{"title":"Pay?"}',
56
+ };
57
+ }
58
+
59
+ // The run journal's waitpoint read: one pending approval per run.
60
+ function waitpointStore() {
61
+ return {
62
+ listWaitpointsForRuns: vi.fn((runIds: string[]) =>
63
+ Promise.resolve(
64
+ new Map(
65
+ runIds.map((runId) => [runId, [waitpointRow(`wp-${runId}`, runId)]]),
66
+ ),
67
+ ),
68
+ ),
69
+ };
70
+ }
71
+
37
72
  function fakeRuntime() {
38
73
  return {
39
74
  webhookEndpoint: vi.fn(() => Promise.resolve(null)),
@@ -43,6 +78,9 @@ function fakeRuntime() {
43
78
  run: vi.fn(() => Promise.resolve(null)),
44
79
  fire: vi.fn(() => Promise.resolve({})),
45
80
  rerun: vi.fn(() => Promise.resolve({})),
81
+ waitingRuns: vi.fn((): Promise<unknown[]> => Promise.resolve([])),
82
+ waitpointsForRun: vi.fn(() => Promise.resolve([{ id: "wp-2" }])),
83
+ store: vi.fn(() => Promise.resolve(waitpointStore())),
46
84
  testStep: vi.fn(() => Promise.resolve({})),
47
85
  stepOutputTree: vi.fn(() => Promise.resolve({})),
48
86
  blockResolutions: vi.fn(() => Promise.resolve([])),
@@ -78,6 +116,7 @@ function build() {
78
116
  queries: resolvers.WorkflowRuntimeQueries,
79
117
  mutations: resolvers.WorkflowRuntimeMutations,
80
118
  secretRecord: resolvers.SecretRecord,
119
+ runRecord: resolvers.WorkflowRunRecord,
81
120
  };
82
121
  }
83
122
 
@@ -367,3 +406,70 @@ describe("piece search", () => {
367
406
  expect(runtime.searchPieces).not.toHaveBeenCalled();
368
407
  });
369
408
  });
409
+
410
+ describe("waitpoints", () => {
411
+ it("serves waiting runs with the waitpoints the runtime listed", async () => {
412
+ const { runtime, queries, runRecord } = build();
413
+ runtime.waitingRuns.mockResolvedValueOnce([
414
+ {
415
+ run: {
416
+ row: { id: "run-1", status: "WAITING", trigger_payload: null },
417
+ steps: [],
418
+ },
419
+ waitpoints: [{ id: "wp-1" }],
420
+ },
421
+ ]);
422
+
423
+ const runs = (await queries.waitingRuns(
424
+ {},
425
+ { driveId: "drive-1", first: 10 },
426
+ CTX,
427
+ )) as { id: string }[];
428
+
429
+ expect(runtime.waitingRuns).toHaveBeenCalledWith(
430
+ { driveId: "drive-1", workflowId: undefined, first: 10 },
431
+ CTX,
432
+ );
433
+ expect(await runRecord.waitpoints(runs[0], {}, CTX)).toEqual([
434
+ { id: "wp-1" },
435
+ ]);
436
+ expect(runtime.waitpointsForRun).not.toHaveBeenCalled();
437
+ });
438
+
439
+ it("reads the waitpoints of every run in a request with one store call", async () => {
440
+ const { runtime, runRecord } = build();
441
+ const store = waitpointStore();
442
+ runtime.store.mockResolvedValueOnce(store);
443
+ const ctx = { ...CTX } as Context;
444
+ const [first, second, again] = (await Promise.all([
445
+ runRecord.waitpoints({ id: "run-1" }, {}, ctx),
446
+ runRecord.waitpoints({ id: "run-2" }, {}, ctx),
447
+ runRecord.waitpoints({ id: "run-1" }, {}, ctx),
448
+ ])) as Array<Array<{ id: string }>>;
449
+
450
+ expect(first).toEqual([
451
+ expect.objectContaining({
452
+ id: "wp-run-1",
453
+ runId: "run-1",
454
+ kind: "approval",
455
+ approval: { title: "Pay?" },
456
+ }),
457
+ ]);
458
+ expect(second!.map((waitpoint) => waitpoint.id)).toEqual(["wp-run-2"]);
459
+ expect(again).toBe(first);
460
+ expect(runtime.store).toHaveBeenCalledTimes(1);
461
+ expect(store.listWaitpointsForRuns).toHaveBeenCalledWith([
462
+ "run-1",
463
+ "run-2",
464
+ ]);
465
+ // The parent resolver served the run; no second run read.
466
+ expect(runtime.waitpointsForRun).not.toHaveBeenCalled();
467
+ expect(runtime.run).not.toHaveBeenCalled();
468
+ });
469
+
470
+ it("serves no waitpoints when the run journal is unavailable", async () => {
471
+ const { runtime, runRecord } = build();
472
+ runtime.store.mockResolvedValueOnce(undefined as never);
473
+ expect(await runRecord.waitpoints({ id: "run-9" }, {}, CTX)).toEqual([]);
474
+ });
475
+ });