@re-cinq/floor-studio 0.11.4 → 0.13.0

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 (82) hide show
  1. package/README.md +46 -9
  2. package/dist/backend/collection-view.js +2 -2
  3. package/dist/backend/floor-answers.d.ts +14 -0
  4. package/dist/backend/floor-answers.js +39 -0
  5. package/dist/backend/floor-blob-routes.d.ts +9 -0
  6. package/dist/backend/floor-blob-routes.js +30 -0
  7. package/dist/backend/floor-brief-route.d.ts +26 -0
  8. package/dist/backend/floor-brief-route.js +21 -0
  9. package/dist/backend/floor-connection-request.d.ts +6 -0
  10. package/dist/backend/floor-connection-request.js +9 -0
  11. package/dist/backend/floor-credentials.d.ts +16 -0
  12. package/dist/backend/floor-credentials.js +14 -0
  13. package/dist/backend/floor-event-routes.d.ts +14 -0
  14. package/dist/backend/floor-event-routes.js +80 -0
  15. package/dist/backend/floor-records-route.d.ts +3 -0
  16. package/dist/backend/floor-records-route.js +22 -0
  17. package/dist/backend/floor-request-body.d.ts +9 -0
  18. package/dist/backend/floor-request-body.js +30 -0
  19. package/dist/backend/floor-route.d.ts +12 -0
  20. package/dist/backend/floor-route.js +41 -0
  21. package/dist/backend/floor-start-route.d.ts +4 -0
  22. package/dist/backend/floor-start-route.js +21 -0
  23. package/dist/backend/floor-visits.d.ts +10 -0
  24. package/dist/backend/floor-visits.js +29 -0
  25. package/dist/backend/guard.d.ts +1 -0
  26. package/dist/backend/guard.js +1 -1
  27. package/dist/backend/parse-json-text.d.ts +1 -0
  28. package/dist/backend/parse-json-text.js +10 -0
  29. package/dist/backend/past-test-run-state.js +22 -4
  30. package/dist/backend/past-test-runs.js +2 -9
  31. package/dist/backend/requests.d.ts +10 -1
  32. package/dist/backend/requests.js +2 -1
  33. package/dist/backend/start-studio.d.ts +17 -0
  34. package/dist/backend/start-studio.js +45 -15
  35. package/dist/backend/test-floor-server.d.ts +27 -0
  36. package/dist/backend/test-floor-server.js +30 -0
  37. package/dist/backend/test-floor-token.d.ts +1 -0
  38. package/dist/backend/test-floor-token.js +19 -0
  39. package/dist/backend/test-run-folder.js +8 -5
  40. package/dist/backend/test-run-session.d.ts +3 -0
  41. package/dist/backend/test-run-session.js +56 -10
  42. package/dist/protocol.d.ts +13 -1
  43. package/dist/protocol.js +2 -1
  44. package/dist/shell/arguments.d.ts +2 -0
  45. package/dist/shell/arguments.js +12 -7
  46. package/dist/shell/loopback-server.d.ts +6 -0
  47. package/dist/shell/loopback-server.js +13 -0
  48. package/dist/shell/static-files.js +3 -6
  49. package/dist/shell/studio-command.d.ts +1 -1
  50. package/dist/shell/studio-command.js +24 -7
  51. package/dist/test-floor/blob-store.d.ts +10 -0
  52. package/dist/test-floor/blob-store.js +29 -0
  53. package/dist/test-floor/dispatch-queue.d.ts +19 -0
  54. package/dist/test-floor/dispatch-queue.js +90 -0
  55. package/dist/test-floor/visit-brief.d.ts +12 -0
  56. package/dist/test-floor/visit-brief.js +57 -0
  57. package/dist/test-floor/visit-tokens.d.ts +5 -0
  58. package/dist/test-floor/visit-tokens.js +12 -0
  59. package/dist/test-floor/worker-answer.d.ts +8 -0
  60. package/dist/test-floor/worker-answer.js +14 -0
  61. package/dist/test-run/event-answer.js +2 -1
  62. package/dist/test-run/outcome-fields.d.ts +2 -0
  63. package/dist/test-run/outcome-fields.js +3 -1
  64. package/dist/test-run/past-state.d.ts +7 -1
  65. package/dist/test-run/past-state.js +6 -2
  66. package/dist/test-run/stand-in-actions.d.ts +1 -0
  67. package/dist/test-run/stand-in-actions.js +6 -3
  68. package/dist/test-run/stand-in-report.js +3 -6
  69. package/dist/test-run/test-run-state.d.ts +5 -1
  70. package/dist/test-run/test-visit.d.ts +6 -0
  71. package/dist/test-run/timeline.d.ts +2 -1
  72. package/dist/test-run/visit-kind.d.ts +2 -1
  73. package/dist/test-run/visit-kind.js +6 -2
  74. package/dist/test-run/visit-record.d.ts +1 -0
  75. package/dist/test-run/visit-record.js +3 -3
  76. package/dist/view.d.ts +1 -0
  77. package/dist/web/assets/index-C8uog-4Z.css +1 -0
  78. package/dist/web/assets/index-CfJcNJKZ.js +195 -0
  79. package/dist/web/index.html +2 -2
  80. package/package.json +6 -5
  81. package/dist/web/assets/index-C5eUTmhR.css +0 -1
  82. package/dist/web/assets/index-mRcd501r.js +0 -195
@@ -0,0 +1,21 @@
1
+ import { startRunSchema } from "@re-cinq/floor-pipeline/wire-schemas";
2
+ import { answerBadRequest, answerConflict, answerJson, answerNotFound, answerRefusalWith, CREATED } from "./floor-answers.js";
3
+ import { answerBody } from "./floor-request-body.js";
4
+ export const startRouteOf = (visits, startFromVisit) => ({
5
+ method: "POST",
6
+ pattern: /^\/assembly-lines\/([^/]+)\/start$/,
7
+ visitsToo: true,
8
+ answer: (request, response, params, credentials) => answerBody(request, response, { schema: startRunSchema, invalidDetail: "invalid start request" }, async (body) => {
9
+ if (credentials.kind !== "visit")
10
+ return answerBadRequest(response, "the Studio test floor starts a run only from a visit's token");
11
+ const floorVisit = visits.visitOf(credentials.visitId);
12
+ if (!floorVisit)
13
+ return answerNotFound(response, `no station run "${credentials.visitId}"`);
14
+ if (floorVisit.ended)
15
+ return answerConflict(response, `station run "${credentials.visitId}" is already done, so it starts no run`);
16
+ if (body.entry !== undefined)
17
+ return answerBadRequest(response, "the Studio test floor starts a line at its entry");
18
+ await startFromVisit(floorVisit, params[0], body.startItems).then((run) => answerJson(response, { joined: false, run }, CREATED), answerRefusalWith(response, answerBadRequest));
19
+ }),
20
+ });
21
+ //# sourceMappingURL=floor-start-route.js.map
@@ -0,0 +1,10 @@
1
+ import type { Item, RunView } from "@re-cinq/floor-contracts";
2
+ import type { StudioContext } from "./requests.js";
3
+ import type { FloorVisit, FloorVisits } from "./floor-brief-route.js";
4
+ import type { StandInAnswer } from "../test-run/stand-in-report.js";
5
+ import type { TestRunSession } from "./test-run-session.js";
6
+ export type ReportFromWorker = (floorVisitId: string, answer: StandInAnswer, worker?: string) => Promise<void>;
7
+ export type StartFromVisit = (floorVisit: FloorVisit, lineId: string, startItems: Record<string, Item>) => Promise<RunView>;
8
+ export declare const workerStartOf: (context: StudioContext) => StartFromVisit;
9
+ export declare const workerReportOf: (testRuns: ReadonlyMap<string, TestRunSession>) => ReportFromWorker;
10
+ export declare const floorVisitsOf: (testRuns: ReadonlyMap<string, TestRunSession>) => FloorVisits;
@@ -0,0 +1,29 @@
1
+ import { dirname, join } from "node:path";
2
+ import { definitionHash } from "@re-cinq/floor-assembly-lines";
3
+ import { startItemsOf } from "../test-run/start-items.js";
4
+ import { readTestLine } from "./read-test-line.js";
5
+ import { startTestRun } from "./test-run-session.js";
6
+ import { SNAPSHOT_FOLDER } from "./test-run-snapshot.js";
7
+ export const workerStartOf = (context) => async ({ runFolder, permission }, lineId, startItems) => {
8
+ const collectionDir = join(runFolder, SNAPSHOT_FOLDER);
9
+ const entered = Object.fromEntries(Object.entries(startItems).map(([name, posted]) => [name, posted.ref]));
10
+ const session = await startTestRun(context, { collectionDir, lineId, workspace: dirname(runFolder), entered, permission });
11
+ const line = await readTestLine(collectionDir, lineId);
12
+ context.testRuns.set(session.id, session);
13
+ return { id: session.id, lineId, lineHash: definitionHash(line.body), repo: null, subjectKey: null, startItems: startItemsOf(line, entered).items, outcome: null, reason: null, createdAt: session.startedAt, finishedAt: null };
14
+ };
15
+ export const workerReportOf = (testRuns) => async (floorVisitId, answer, worker) => {
16
+ const owner = [...testRuns.values()].find((session) => session.floorVisit(floorVisitId));
17
+ await owner?.reportFromWorker(floorVisitId, answer, worker);
18
+ };
19
+ export const floorVisitsOf = (testRuns) => ({
20
+ visitOf: (floorVisitId) => {
21
+ for (const session of testRuns.values()) {
22
+ const found = session.floorVisit(floorVisitId);
23
+ if (found)
24
+ return found;
25
+ }
26
+ return undefined;
27
+ },
28
+ });
29
+ //# sourceMappingURL=floor-visits.js.map
@@ -11,4 +11,5 @@ export interface UpgradeRefusal {
11
11
  reason: string;
12
12
  }
13
13
  export declare function upgradeRefusal({ url, origin, token, origins }: UpgradeAsked): UpgradeRefusal | undefined;
14
+ export declare function isSameToken(given: string, token: string): boolean;
14
15
  export {};
@@ -14,7 +14,7 @@ function tokenOf(url) {
14
14
  return new URL(url ?? "/", "http://localhost").searchParams.get("token") ?? "";
15
15
  }
16
16
  // Hashed first so the two buffers are as long as each other: timingSafeEqual throws on unequal lengths, and a length is a clue.
17
- function isSameToken(given, token) {
17
+ export function isSameToken(given, token) {
18
18
  return timingSafeEqual(createHash("sha256").update(given).digest(), createHash("sha256").update(token).digest());
19
19
  }
20
20
  //# sourceMappingURL=guard.js.map
@@ -0,0 +1 @@
1
+ export declare function parseJsonText<Shape>(raw: string): Shape | null;
@@ -0,0 +1,10 @@
1
+ // Parses JSON text, answering null when the text is not JSON.
2
+ export function parseJsonText(raw) {
3
+ try {
4
+ return JSON.parse(raw);
5
+ }
6
+ catch {
7
+ return null;
8
+ }
9
+ }
10
+ //# sourceMappingURL=parse-json-text.js.map
@@ -1,8 +1,11 @@
1
- // Reads a past test run's state back from its folder: run.json, timeline.jsonl and visits/*/visit.json.
1
+ // Reads a past test run's state back from its folder: run.json, timeline.jsonl, visits/*/visit.json and the definitions/ snapshot.
2
2
  import { readdir, readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { pastStateOf } from "../test-run/past-state.js";
5
+ import { parseJsonText } from "./parse-json-text.js";
5
6
  import { pastTestRuns } from "./past-test-runs.js";
7
+ import { readTestLine } from "./read-test-line.js";
8
+ import { SNAPSHOT_FOLDER } from "./test-run-snapshot.js";
6
9
  import { RUN_FILE, TIMELINE_FILE } from "./test-run-timeline.js";
7
10
  import { visitFolderOf } from "./test-run-visit-files.js";
8
11
  export async function readPastRun(collectionDir, folder) {
@@ -11,9 +14,24 @@ export async function readPastRun(collectionDir, folder) {
11
14
  }
12
15
  async function stateIn(folder) {
13
16
  const summary = JSON.parse(await readFile(join(folder, RUN_FILE), "utf8"));
14
- const timeline = (await readFile(join(folder, TIMELINE_FILE), "utf8")).split("\n").filter(Boolean).map((line) => JSON.parse(line));
17
+ const [timeline, records, line] = await Promise.all([
18
+ timelineEntriesIn(folder),
19
+ visitRecordsIn(folder),
20
+ readTestLine(join(folder, SNAPSHOT_FOLDER), summary.line).catch(() => undefined),
21
+ ]);
22
+ return pastStateOf(folder, summary, timeline, { records, line });
23
+ }
24
+ async function timelineEntriesIn(folder) {
25
+ const lines = (await readFile(join(folder, TIMELINE_FILE), "utf8")).split("\n").filter(Boolean);
26
+ return lines.map((line) => parseJsonText(line)).filter((entry) => entry !== null);
27
+ }
28
+ async function visitRecordsIn(folder) {
15
29
  const ids = await readdir(join(folder, "visits")).catch(() => []);
16
- const records = await Promise.all(ids.map(async (id) => JSON.parse(await readFile(join(visitFolderOf(folder, id), "visit.json"), "utf8").catch(() => "null"))));
17
- return pastStateOf(folder, summary, timeline, Object.fromEntries(records.filter((record) => record !== null).map((record) => [record.id, record])));
30
+ const found = await Promise.all(ids.map((id) => visitRecordIn(visitFolderOf(folder, id))));
31
+ return Object.fromEntries(found.filter((record) => record !== null).map((record) => [record.id, record]));
32
+ }
33
+ async function visitRecordIn(visitFolder) {
34
+ const text = await readFile(join(visitFolder, "visit.json"), "utf8").catch(() => undefined);
35
+ return text === undefined ? null : parseJsonText(text);
18
36
  }
19
37
  //# sourceMappingURL=past-test-run-state.js.map
@@ -3,6 +3,7 @@ import { readdir, readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { pastListingOf } from "../test-run/past-listing.js";
5
5
  import { rememberedWorkspaces } from "./last-tests.js";
6
+ import { parseJsonText } from "./parse-json-text.js";
6
7
  import { RUN_FILE } from "./test-run-timeline.js";
7
8
  export async function pastTestRuns(collectionDir) {
8
9
  const remembered = await rememberedWorkspaces(collectionDir);
@@ -17,15 +18,7 @@ async function runsOf(line, workspace) {
17
18
  }
18
19
  async function listingIn(folder) {
19
20
  const raw = await readFile(join(folder, RUN_FILE), "utf8").catch(() => undefined);
20
- const summary = raw === undefined ? null : parseSummary(raw);
21
+ const summary = raw === undefined ? null : parseJsonText(raw);
21
22
  return summary && pastListingOf(folder, summary);
22
23
  }
23
- function parseSummary(raw) {
24
- try {
25
- return JSON.parse(raw);
26
- }
27
- catch {
28
- return null;
29
- }
30
- }
31
24
  //# sourceMappingURL=past-test-runs.js.map
@@ -7,9 +7,11 @@ import { type RunCancelRequest } from "./run-cancel-request.js";
7
7
  import { type RunStartRequest } from "./run-start-request.js";
8
8
  import { type RunReadRequest } from "./run-read-request.js";
9
9
  import { type TestListRequest } from "./test-list-requests.js";
10
+ import { type FloorConnectionRequest } from "./floor-connection-request.js";
10
11
  import { type TestLastRequest } from "./test-last-requests.js";
11
12
  import { type FolderListRequest, type TestEventRequest, type FolderOpenRequest, type TestCancelRequest, type TestPreviewRequest, type TestReadRequest, type TestReportRequest, type TestStartRequest } from "./test-run-requests.js";
12
13
  import type { TestRunSession } from "./test-run-session.js";
14
+ import type { DispatchQueue } from "../test-floor/dispatch-queue.js";
13
15
  import type { RunRecord, RunTranscript } from "../run/run-records.js";
14
16
  export interface StudioContext {
15
17
  readCollection(): Promise<CollectionView>;
@@ -33,6 +35,13 @@ export interface StudioContext {
33
35
  testRuns: Map<string, TestRunSession>;
34
36
  /** Environment laid over the studio's own for each started process. */
35
37
  runEnv?: Record<string, string>;
38
+ /** The test floor's queue: a service visit's dispatch waits there for the user's own worker. */
39
+ testFloor: DispatchQueue;
40
+ /** Where the test floor is serving; absent while it is not. */
41
+ floorConnection?: {
42
+ url: string;
43
+ token: string;
44
+ };
36
45
  /** Sends a frame to every open socket. */
37
46
  broadcast(frame: ServerFrame): void;
38
47
  /** Opens a folder in the desktop's file manager. */
@@ -52,6 +61,6 @@ type CollectionRead = Extract<Request, {
52
61
  type: "collection.read";
53
62
  }>;
54
63
  /** One handler for each request type: a test holds the list to `REQUEST_TYPES`. */
55
- export declare const HANDLERS: (Handler<CollectionRead> | Handler<AgentWrite> | Handler<ExtraWrite> | Handler<FixtureWrite> | Handler<FixtureRead> | Handler<RunPreviewRequest> | Handler<RunStartRequest> | Handler<RunCancelRequest> | Handler<RunReadRequest> | Handler<TestStartRequest> | Handler<TestReportRequest> | Handler<TestCancelRequest> | Handler<TestReadRequest> | Handler<TestPreviewRequest> | Handler<FolderOpenRequest> | Handler<FolderListRequest> | Handler<TestEventRequest> | Handler<TestLastRequest> | Handler<TestListRequest>)[];
64
+ export declare const HANDLERS: (Handler<CollectionRead> | Handler<AgentWrite> | Handler<ExtraWrite> | Handler<FixtureWrite> | Handler<FixtureRead> | Handler<RunPreviewRequest> | Handler<RunStartRequest> | Handler<RunCancelRequest> | Handler<RunReadRequest> | Handler<TestStartRequest> | Handler<TestReportRequest> | Handler<TestCancelRequest> | Handler<TestReadRequest> | Handler<TestPreviewRequest> | Handler<FolderOpenRequest> | Handler<FolderListRequest> | Handler<TestEventRequest> | Handler<TestLastRequest> | Handler<TestListRequest> | Handler<FloorConnectionRequest>)[];
56
65
  export declare function answerFrame(text: string, context: StudioContext): Promise<ServerFrame>;
57
66
  export {};
@@ -8,6 +8,7 @@ import { runCancelHandler } from "./run-cancel-request.js";
8
8
  import { runStartHandler } from "./run-start-request.js";
9
9
  import { runReadHandler } from "./run-read-request.js";
10
10
  import { testListHandler } from "./test-list-requests.js";
11
+ import { floorConnectionHandler } from "./floor-connection-request.js";
11
12
  import { testLastHandler } from "./test-last-requests.js";
12
13
  import { folderListHandler, testEventHandler, folderOpenHandler, testCancelHandler, testPreviewHandler, testReadHandler, testReportHandler, testStartHandler } from "./test-run-requests.js";
13
14
  function agentFileOf({ lines }, lineId, agentName) {
@@ -40,7 +41,7 @@ const extraWrite = {
40
41
  };
41
42
  const collectionRead = { type: "collection.read", handle: (context) => context.readCollection() };
42
43
  /** One handler for each request type: a test holds the list to `REQUEST_TYPES`. */
43
- export const HANDLERS = [collectionRead, agentWrite, extraWrite, fixtureWrite, fixtureRead, runPreviewHandler, runStartHandler, runCancelHandler, runReadHandler, testStartHandler, testReportHandler, testCancelHandler, testReadHandler, testPreviewHandler, folderOpenHandler, folderListHandler, testEventHandler, testLastHandler, testListHandler];
44
+ export const HANDLERS = [collectionRead, agentWrite, extraWrite, fixtureWrite, fixtureRead, runPreviewHandler, runStartHandler, runCancelHandler, runReadHandler, testStartHandler, testReportHandler, testCancelHandler, testReadHandler, testPreviewHandler, folderOpenHandler, folderListHandler, testEventHandler, testLastHandler, testListHandler, floorConnectionHandler];
44
45
  export async function answerFrame(text, context) {
45
46
  const held = parsedJson(text);
46
47
  const id = idOf(held);
@@ -1,3 +1,6 @@
1
+ import { type ReportFromWorker, type StartFromVisit } from "./floor-visits.js";
2
+ import type { FloorVisits } from "./floor-brief-route.js";
3
+ import { type DispatchQueue } from "../test-floor/dispatch-queue.js";
1
4
  export interface StudioOptions {
2
5
  dir: string;
3
6
  /** 0 picks a free port. */
@@ -18,6 +21,20 @@ export interface Studio {
18
21
  token: string;
19
22
  /** The sockets that passed the token and origin check and are still open. */
20
23
  pageCount(): number;
24
+ /** The waiting visits of the test runs, for the test floor to answer briefs from. */
25
+ floorVisits: FloorVisits;
26
+ /** The queue of work the test floor hands to custom stations. */
27
+ testFloor: DispatchQueue;
28
+ /** Pushes the state of the test run of each floor visit, after its dispatch changed. */
29
+ dispatchChanged(floorVisitIds: string[]): void;
30
+ /** Hands a worker's report to the test run that owns the visit. */
31
+ reportFromWorker: ReportFromWorker;
32
+ startFromVisit: StartFromVisit;
33
+ /** Tells the pages where the test floor listens, once it does. */
34
+ serveFloor(connection: {
35
+ url: string;
36
+ token: string;
37
+ }): void;
21
38
  close(): Promise<void>;
22
39
  }
23
40
  export declare function startStudio(options: StudioOptions): Promise<Studio>;
@@ -9,32 +9,25 @@ import { WebSocket, WebSocketServer } from "ws";
9
9
  import { PROTOCOL_VERSION } from "../protocol.js";
10
10
  import { upgradeRefusal } from "./guard.js";
11
11
  import { editedAgentText, textVersion, withOneNewline } from "./agent-file-text.js";
12
+ import { LOOPBACK, listenOnLoopback } from "../shell/loopback-server.js";
12
13
  import { openOnDesktop } from "../shell/open-browser.js";
13
14
  import { fixtureFilesIn } from "./fixture-files.js";
14
15
  import { runFilesIn } from "./run-files.js";
15
16
  import { answerFrame } from "./requests.js";
16
17
  import { readCollectionView } from "./read-collection-view.js";
17
18
  import { watchCollection } from "./watcher.js";
18
- /** Never `0.0.0.0`: the backend writes files and starts processes. */
19
- const LOOPBACK = "127.0.0.1";
19
+ import { floorVisitsOf, workerReportOf, workerStartOf } from "./floor-visits.js";
20
+ import { createDispatchQueue } from "../test-floor/dispatch-queue.js";
20
21
  const MAX_FRAME_BYTES = 4_194_304;
21
22
  const TOKEN_BYTES = 32;
22
23
  const GOING_AWAY = 1001;
23
24
  const UPGRADE_REQUIRED = 426;
24
25
  export async function startStudio(options) {
25
- const { dir, hostKeys, origins = [] } = options;
26
+ const { dir, origins = [] } = options;
26
27
  enforce((await stat(dir).catch(() => undefined))?.isDirectory(), `${dir} is not a directory`);
27
28
  const token = randomBytes(TOKEN_BYTES).toString("hex");
28
29
  const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
29
- const allHostKeys = async () => [...hostKeys, ...(await hostKeysIn(dir))];
30
- const readCollection = () => readCollectionView(dir, hostKeys);
31
- const writeAgent = async (file, edit) => {
32
- const path = join(dir, file);
33
- const text = editedAgentText(file, await readFile(path, "utf8"), edit);
34
- readAgentFile(basename(file, ".md"), text, await allHostKeys());
35
- await writeFile(path, text);
36
- };
37
- const context = { readCollection, writeAgent, writeExtra: (file, edit) => writeExtraFile(join(dir, file), edit), ...fixtureFilesIn(dir), ...runFilesIn(dir), runs: new Map(), collectionDir: dir, testRuns: new Map(), runEnv: options.runEnv, broadcast: (frame) => sockets.clients.forEach((socket) => send(socket, frame)), openFolder: options.openFolder ?? openOnDesktop };
30
+ const context = contextOf(options, sockets);
38
31
  const server = createServer(refuseHttp);
39
32
  server.on("upgrade", (request, socket, head) => {
40
33
  const refusal = upgradeRefusal({ url: request.url, origin: request.headers.origin, token, origins });
@@ -43,15 +36,52 @@ export async function startStudio(options) {
43
36
  sockets.handleUpgrade(request, socket, head, (opened) => sockets.emit("connection", opened, request));
44
37
  });
45
38
  sockets.on("connection", (socket) => serve(socket, context));
46
- const watcher = watchCollection(dir, () => void pushCollection(sockets, readCollection), options.watchDebounceMs);
47
- await new Promise((resolve) => server.listen(options.port, LOOPBACK, resolve));
39
+ const watcher = watchCollection(dir, () => void pushCollection(sockets, context.readCollection), options.watchDebounceMs);
40
+ const port = await listenOnLoopback(server, options.port);
48
41
  return {
49
- url: `ws://${LOOPBACK}:${server.address().port}`,
42
+ url: `ws://${LOOPBACK}:${port}`,
50
43
  token,
51
44
  pageCount: () => sockets.clients.size,
45
+ ...floorSideOf(context),
52
46
  close: () => closed({ watcher, sockets, server, runs: context.runs }),
53
47
  };
54
48
  }
49
+ function contextOf({ dir, hostKeys, runEnv, openFolder }, sockets) {
50
+ return {
51
+ readCollection: () => readCollectionView(dir, hostKeys),
52
+ writeAgent: (file, edit) => writeAgentFile({ dir, hostKeys, file, edit }),
53
+ writeExtra: (file, edit) => writeExtraFile(join(dir, file), edit),
54
+ ...fixtureFilesIn(dir),
55
+ ...runFilesIn(dir),
56
+ runs: new Map(),
57
+ collectionDir: dir,
58
+ testRuns: new Map(),
59
+ testFloor: createDispatchQueue(() => new Date()),
60
+ runEnv,
61
+ broadcast: (frame) => sockets.clients.forEach((socket) => send(socket, frame)),
62
+ openFolder: openFolder ?? openOnDesktop,
63
+ };
64
+ }
65
+ async function writeAgentFile({ dir, hostKeys, file, edit }) {
66
+ const path = join(dir, file);
67
+ const text = editedAgentText(file, await readFile(path, "utf8"), edit);
68
+ readAgentFile(basename(file, ".md"), text, [...hostKeys, ...(await hostKeysIn(dir))]);
69
+ await writeFile(path, text);
70
+ }
71
+ function floorSideOf(context) {
72
+ return {
73
+ floorVisits: floorVisitsOf(context.testRuns),
74
+ testFloor: context.testFloor,
75
+ dispatchChanged: (floorVisitIds) => changedRunsOf(context, floorVisitIds),
76
+ reportFromWorker: workerReportOf(context.testRuns),
77
+ startFromVisit: workerStartOf(context),
78
+ serveFloor: (connection) => void (context.floorConnection = connection),
79
+ };
80
+ }
81
+ function changedRunsOf({ testRuns, broadcast }, floorVisitIds) {
82
+ const touched = [...testRuns.values()].filter((session) => floorVisitIds.some((floorVisitId) => session.floorVisit(floorVisitId)));
83
+ touched.forEach((session) => broadcast({ type: "test.changed", run: session.id, state: session.state() }));
84
+ }
55
85
  async function writeExtraFile(path, { text, version }) {
56
86
  enforce(version === textVersion(await readFile(path, "utf8")), `${basename(path)} changed on disk since it was read`);
57
87
  await writeFile(path, withOneNewline(text));
@@ -0,0 +1,27 @@
1
+ import type { BlobStore } from "../test-floor/blob-store.js";
2
+ import type { DispatchQueue } from "../test-floor/dispatch-queue.js";
3
+ import type { VisitTokens } from "../test-floor/visit-tokens.js";
4
+ import type { ReportFromWorker, StartFromVisit } from "./floor-visits.js";
5
+ import { type FloorVisits } from "./floor-brief-route.js";
6
+ export type { FloorVisit, FloorVisits } from "./floor-brief-route.js";
7
+ export interface TestFloorOptions {
8
+ port: number;
9
+ token: string;
10
+ /** What a claim is answered from. */
11
+ queue: DispatchQueue;
12
+ visits: FloorVisits;
13
+ tokens: VisitTokens;
14
+ blobs: BlobStore;
15
+ /** Told which visits a claim handed a dispatch to. */
16
+ dispatchChanged: (floorVisitIds: string[]) => void;
17
+ /** Hands a worker's report to the run that owns the visit. */
18
+ reportFromWorker: ReportFromWorker;
19
+ /** Starts a run of a line for a worker, from its visit. */
20
+ startFromVisit: StartFromVisit;
21
+ }
22
+ export interface TestFloor {
23
+ /** `http://127.0.0.1:<port>`: where a worker sends its requests. */
24
+ url: string;
25
+ close(): Promise<void>;
26
+ }
27
+ export declare function startTestFloor({ port, token, queue, visits, tokens, blobs, dispatchChanged, reportFromWorker, startFromVisit }: TestFloorOptions): Promise<TestFloor>;
@@ -0,0 +1,30 @@
1
+ // The test floor: the station-facing part of the floor's API, served over plain HTTP on the loopback address behind a service token, so a custom station's worker can be tested locally.
2
+ import { createServer } from "node:http";
3
+ import { enforce } from "@re-cinq/floor-assembly-lines";
4
+ import { closeServer, listenOnLoopback, LOOPBACK } from "../shell/loopback-server.js";
5
+ import { blobRoutesOf } from "./floor-blob-routes.js";
6
+ import { briefRouteOf } from "./floor-brief-route.js";
7
+ import { recordsRouteOf } from "./floor-records-route.js";
8
+ import { startRouteOf } from "./floor-start-route.js";
9
+ import { answerInternalError, answerUnauthorized } from "./floor-answers.js";
10
+ import { credentialsOf } from "./floor-credentials.js";
11
+ import { eventRoutesOf } from "./floor-event-routes.js";
12
+ import { answerServed } from "./floor-route.js";
13
+ export async function startTestFloor({ port, token, queue, visits, tokens, blobs, dispatchChanged, reportFromWorker, startFromVisit }) {
14
+ enforce(token !== "", "the test floor needs a service token to start");
15
+ const own = { url: "" };
16
+ const givenNeeds = new Map();
17
+ const routes = [...eventRoutesOf({ queue, visits, blobs, dispatchChanged, reportFromWorker }), briefRouteOf({ visits, tokens, blobs, givenNeeds, floorUrl: () => own.url }), ...blobRoutesOf({ blobs, givenNeeds }), recordsRouteOf(visits), startRouteOf(visits, startFromVisit)];
18
+ const server = createServer((request, response) => {
19
+ const credentials = credentialsOf(request, { token, tokens });
20
+ if (!credentials)
21
+ return answerUnauthorized(response);
22
+ answerServed(routes, credentials, request, response).catch(() => answerInternalError(response));
23
+ });
24
+ const boundPort = await listenOnLoopback(server, port).catch((error) => {
25
+ throw error.code === "EADDRINUSE" ? new Error(`the test floor cannot listen on ${LOOPBACK}:${port}: the port is in use`) : error;
26
+ });
27
+ own.url = `http://${LOOPBACK}:${boundPort}`;
28
+ return { url: own.url, close: () => closeServer(server) };
29
+ }
30
+ //# sourceMappingURL=test-floor-server.js.map
@@ -0,0 +1 @@
1
+ export declare function testFloorToken(collectionDir: string): Promise<string>;
@@ -0,0 +1,19 @@
1
+ // The service token of a collection's test floor, kept in its studio folder so a worker's token survives a restart.
2
+ import { randomBytes } from "node:crypto";
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { parseJsonText } from "./parse-json-text.js";
6
+ import { storeFolderIn } from "./store-folder.js";
7
+ import { jsonFileText } from "./test-run-folder.js";
8
+ const TOKEN_BYTES = 32;
9
+ export async function testFloorToken(collectionDir) {
10
+ const store = await storeFolderIn(collectionDir);
11
+ const tokenFile = join(store, "test-floor.json");
12
+ const stored = parseJsonText(await readFile(tokenFile, "utf8").catch(() => ""));
13
+ if (typeof stored?.token === "string" && stored.token)
14
+ return stored.token;
15
+ const token = randomBytes(TOKEN_BYTES).toString("hex");
16
+ await writeFile(tokenFile, jsonFileText({ token }));
17
+ return token;
18
+ }
19
+ //# sourceMappingURL=test-floor-token.js.map
@@ -5,12 +5,15 @@ import { enforce } from "@re-cinq/floor-assembly-lines";
5
5
  export async function createRunFolder(workspace, name) {
6
6
  enforceAbsolute(workspace, "the workspace folder");
7
7
  enforce(await isFolder(workspace), `the workspace folder ${workspace} is not a folder on disk`);
8
- const runFolder = join(workspace, name);
9
- await mkdir(runFolder).catch((error) => {
10
- enforce(error.code !== "EEXIST", `${runFolder} already exists, and a test run never reuses a folder`);
11
- throw error;
8
+ return makeFirstFreeFolder(join(workspace, name), 1);
9
+ }
10
+ function makeFirstFreeFolder(wanted, attempt) {
11
+ const candidate = attempt === 1 ? wanted : `${wanted}-${attempt}`;
12
+ return mkdir(candidate).then(() => candidate, (error) => {
13
+ if (error.code !== "EEXIST")
14
+ throw error;
15
+ return makeFirstFreeFolder(wanted, attempt + 1);
12
16
  });
13
- return runFolder;
14
17
  }
15
18
  /** The text of a JSON file in a run folder: indented, one trailing newline. */
16
19
  export function jsonFileText(value) {
@@ -1,6 +1,7 @@
1
1
  import { type SentEvent } from "../test-run/event-answer.js";
2
2
  import { type StandInAnswer } from "../test-run/stand-in-report.js";
3
3
  import type { TestRunState } from "../test-run/test-run-state.js";
4
+ import type { FloorVisit } from "./floor-brief-route.js";
4
5
  import type { StudioContext } from "./requests.js";
5
6
  export interface TestRunStart {
6
7
  collectionDir: string;
@@ -19,5 +20,7 @@ export interface TestRunSession {
19
20
  event(sent: SentEvent): Promise<{
20
21
  answered: string[];
21
22
  }>;
23
+ floorVisit(floorVisitId: string): FloorVisit | undefined;
24
+ reportFromWorker(floorVisitId: string, answer: StandInAnswer, worker?: string): Promise<void>;
22
25
  }
23
26
  export declare function startTestRun(context: StudioContext, start: TestRunStart, clock?: () => Date): Promise<TestRunSession>;
@@ -1,5 +1,6 @@
1
1
  // A local test run in flight: its folder, its snapshot of the collection and the visits the line's walk has opened so far.
2
2
  import { randomUUID } from "node:crypto";
3
+ import { rm } from "node:fs/promises";
3
4
  import { join } from "node:path";
4
5
  import { endsRun, enforce } from "@re-cinq/floor-assembly-lines";
5
6
  import { answeredVisitsOf } from "../test-run/event-answer.js";
@@ -15,7 +16,7 @@ import { waitingActionsOf } from "../test-run/stand-in-actions.js";
15
16
  import { nodeAt, stationAt } from "../test-run/test-line.js";
16
17
  import { modeOf } from "../test-run/timeline.js";
17
18
  import { visitRecordOf } from "../test-run/visit-record.js";
18
- import { visitKindOf } from "../test-run/visit-kind.js";
19
+ import { visitKindOf, waitsForAnswer } from "../test-run/visit-kind.js";
19
20
  import { inOrder } from "./in-order.js";
20
21
  import { readCollectionView } from "./read-collection-view.js";
21
22
  import { readTestLine } from "./read-test-line.js";
@@ -33,6 +34,16 @@ export async function startTestRun(context, start, clock = () => new Date()) {
33
34
  enforceStartable(lineId, liveLine, missing);
34
35
  const startedAt = clock();
35
36
  const folder = await createRunFolder(workspace, runFolderName(lineId, startedAt));
37
+ const work = await openRun(context, start, { folder, startedAt, startItems, clock }).catch(async (error) => {
38
+ await rm(folder, { recursive: true, force: true }).catch(() => undefined);
39
+ throw error;
40
+ });
41
+ void trackStep(work, stepRun(work));
42
+ return sessionOf(work);
43
+ }
44
+ async function openRun(context, start, created) {
45
+ const { folder, startedAt, startItems, clock } = created;
46
+ const { collectionDir, lineId } = start;
36
47
  const snapshotDir = join(folder, SNAPSHOT_FOLDER);
37
48
  await snapshotCollection(collectionDir, folder);
38
49
  const [line, view] = await Promise.all([readTestLine(snapshotDir, lineId), readCollectionView(snapshotDir, [])]);
@@ -40,8 +51,7 @@ export async function startTestRun(context, start, clock = () => new Date()) {
40
51
  const run = { line, startItems, visits: state.visits };
41
52
  const work = { id: randomUUID(), context, start, view, run, state, clock, startedAt: startedAt.toISOString(), cancelled: false, stepping: Promise.resolve(), timelineWrites: inOrder() };
42
53
  await noteInTimeline(work, { "at": startedAt.toISOString(), type: "run_started", line: lineId });
43
- void trackStep(work, stepRun(work));
44
- return sessionOf(work);
54
+ return work;
45
55
  }
46
56
  function sessionOf(work) {
47
57
  return {
@@ -52,10 +62,25 @@ function sessionOf(work) {
52
62
  cancel: () => cancelWork(work),
53
63
  report: (visitId, answer) => reportAnswer(work, visitId, answer),
54
64
  event: (sent) => answerEvent(work, sent),
65
+ floorVisit: (floorVisitId) => floorVisitOf(work, floorVisitId),
66
+ reportFromWorker: (floorVisitId, answer, worker) => reportFromWorker(work, floorVisitId, answer, worker),
55
67
  };
56
68
  }
57
- function stateOf({ state, run }) {
58
- return { ...state, actions: waitingActionsOf(run.line, state.visits), bag: bagEntriesOf(run) };
69
+ function floorVisitOf({ id, run, state, cancelled, start }, floorVisitId) {
70
+ const visit = state.visits.find((candidate) => candidate.floorVisitId === floorVisitId);
71
+ return visit && { run, runId: id, visit, ended: cancelled || visit.report !== null, runFolder: state.folder, permission: start.permission };
72
+ }
73
+ async function reportFromWorker(work, floorVisitId, answer, worker) {
74
+ const { visits } = work.state;
75
+ const visit = visits.find((candidate) => candidate.floorVisitId === floorVisitId);
76
+ enforce(visit, `the run has no floor visit ${floorVisitId}`);
77
+ if (visit.report !== null || work.state.status === "settled")
78
+ return;
79
+ await reportAnswer(work, visit.id, answer, { worker });
80
+ }
81
+ function stateOf({ state, run, context }) {
82
+ const visits = state.visits.map((visit) => (visit.floorVisitId === undefined ? visit : { ...visit, dispatch: context.testFloor.dispatchOf(visit.floorVisitId) }));
83
+ return { ...state, visits, actions: waitingActionsOf(run.line, state.visits), bag: bagEntriesOf(run) };
59
84
  }
60
85
  function cancelWork(work) {
61
86
  const { status } = work.state;
@@ -68,10 +93,13 @@ function cancelWork(work) {
68
93
  cancelRun(work.context.runs, work.agentRun);
69
94
  return work.stepping;
70
95
  }
71
- async function reportAnswer(work, visitId, answer) {
96
+ async function reportAnswer(work, visitId, answer, answeredBy) {
72
97
  const accepted = acceptReport(work, visitId, answer);
73
98
  const written = writeSuppliedFiles(accepted.targets, answer.files ?? {}).catch((cause) => refuseReport(work, accepted, cause));
74
- const stepped = written.then(() => trackStep(work, noteThenStep(work, [accepted])));
99
+ const stepped = written.then(() => {
100
+ accepted.visit.answeredBy = answeredBy;
101
+ return trackStep(work, noteThenStep(work, [accepted]));
102
+ });
75
103
  work.stepping = stepped.catch(() => undefined);
76
104
  return stepped;
77
105
  }
@@ -106,7 +134,7 @@ function enforceTakesAnswers(state) {
106
134
  function acceptReport({ run, state }, visitId, answer) {
107
135
  const visit = state.visits.find(({ id }) => id === visitId);
108
136
  enforce(visit, `the run has no visit ${visitId}`);
109
- enforce(visit.kind === "stand-in", `visit ${visitId} was run by an agent, and a person cannot answer for it`);
137
+ enforce(waitsForAnswer(visit.kind), `visit ${visitId} was run by an agent, and a person cannot answer for it`);
110
138
  enforce(visit.report === null, `visit ${visitId} has already reported ${visit.report?.outcome}`);
111
139
  enforceTakesAnswers(state);
112
140
  enforcePickedFilesOnDisk(answer.files ?? {});
@@ -145,7 +173,7 @@ async function stepRun(work) {
145
173
  return settleRun(work, endingOf(transition));
146
174
  if (transition.kind !== "launch")
147
175
  return;
148
- const visit = openVisit(work, transition);
176
+ const visit = openOnTestFloor(work, openVisit(work, transition));
149
177
  const { state } = work;
150
178
  state.visits.push(visit);
151
179
  if (visit.kind !== "agent")
@@ -156,6 +184,13 @@ async function stepRun(work) {
156
184
  await runAgentStep(work, visit);
157
185
  return stepRun(work);
158
186
  }
187
+ function openOnTestFloor({ context }, visit) {
188
+ if (visit.kind !== "service")
189
+ return visit;
190
+ const floorVisitId = randomUUID();
191
+ context.testFloor.open(floorVisitId, `station:${visit.station}`);
192
+ return { ...visit, floorVisitId };
193
+ }
159
194
  async function runAgentStep(work, visit) {
160
195
  const { context, view, start, state } = work;
161
196
  const onRun = (run) => {
@@ -171,6 +206,9 @@ async function settleRun(work, ending) {
171
206
  const { state } = work;
172
207
  state.status = "settled";
173
208
  state.ending = ending;
209
+ for (const visit of state.visits)
210
+ if (visit.report === null)
211
+ endOnTestFloor(work, visit);
174
212
  await noteInTimeline(work, { "at": work.clock().toISOString(), type: "run_settled", outcome: ending.outcome });
175
213
  }
176
214
  function endingOf(transition) {
@@ -210,9 +248,17 @@ async function noteReported(work, visit, report) {
210
248
  const { state, run } = work;
211
249
  const reportedAt = work.clock().toISOString();
212
250
  visit.reportedAt = reportedAt;
251
+ endOnTestFloor(work, visit);
213
252
  await Promise.all([
214
- noteInTimeline(work, { "at": reportedAt, type: "visit_reported", visit: visit.id, outcome: report.outcome }),
253
+ noteInTimeline(work, { "at": reportedAt, type: "visit_reported", visit: visit.id, outcome: report.outcome, ...workerOf(visit) }),
215
254
  writeVisitRecord(state.folder, visitRecordOf(run.line, visit, report)),
216
255
  ]);
217
256
  }
257
+ function workerOf({ answeredBy }) {
258
+ return answeredBy?.worker === undefined ? {} : { worker: answeredBy.worker };
259
+ }
260
+ function endOnTestFloor({ context }, visit) {
261
+ if (visit.floorVisitId)
262
+ context.testFloor.end(visit.floorVisitId);
263
+ }
218
264
  //# sourceMappingURL=test-run-session.js.map