@roster-lock/match-agent 0.3.1 → 0.4.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 (157) hide show
  1. package/client/dist/assets/index-D2395vmC.css +1 -0
  2. package/client/dist/assets/index-DcKsa72V.js +125 -0
  3. package/client/dist/index.html +2 -2
  4. package/client/e2e/lib/env.ts +50 -0
  5. package/client/e2e/lib/fileDialog.ts +31 -0
  6. package/client/e2e/lib/mockGamepad.ts +71 -0
  7. package/client/e2e/lib/onscreenKeyboard.ts +32 -0
  8. package/client/e2e/playwright.config.ts +48 -0
  9. package/client/e2e/tests/gamepad-only.spec.ts +274 -0
  10. package/client/e2e/tests/keyboard-only.spec.ts +67 -0
  11. package/client/e2e/tsconfig.json +15 -0
  12. package/client/node_modules/.bin/playwright +17 -0
  13. package/client/node_modules/.bin/roster-lock-plugin-manager +17 -0
  14. package/client/node_modules/.vite/deps/@roster-lock_ts-client.js +2 -2
  15. package/client/node_modules/.vite/deps/@roster-lock_types.js +1 -1
  16. package/client/node_modules/.vite/deps/@roster-lock_utils.js +1 -1
  17. package/client/node_modules/.vite/deps/_metadata.json +18 -18
  18. package/client/node_modules/.vite/deps/{chunk-CKYX73LL.js → chunk-3HBL6DQ6.js} +1 -1
  19. package/client/node_modules/.vite/deps/{chunk-CKYX73LL.js.map → chunk-3HBL6DQ6.js.map} +2 -2
  20. package/client/node_modules/.vite/deps/{chunk-EDVVVQBR.js → chunk-QTQN6EZX.js} +2 -2
  21. package/client/node_modules/.vite/deps/chunk-QTQN6EZX.js.map +7 -0
  22. package/client/package.json +4 -1
  23. package/client/src/App.tsx +23 -14
  24. package/client/src/NavBar.tsx +15 -5
  25. package/client/src/api/matchAgent.ts +193 -5
  26. package/client/src/bridge/hostBridge.ts +15 -5
  27. package/client/src/components/FullScreenMenu.tsx +32 -0
  28. package/client/src/components/GameLauncherSettingsForm.tsx +80 -5
  29. package/client/src/components/InputHints.tsx +37 -0
  30. package/client/src/components/OnScreenFileDialog.tsx +83 -0
  31. package/client/src/components/OnScreenKeyboard.tsx +75 -0
  32. package/client/src/components/Selection/PieceCard.tsx +29 -4
  33. package/client/src/components/Selection/PiecePreviewPanel.tsx +48 -0
  34. package/client/src/components/Selection/PieceTypeSection.tsx +124 -46
  35. package/client/src/components/Selection/PlayerSelectionPanel.tsx +1 -5
  36. package/client/src/components/Selection/index.tsx +72 -47
  37. package/client/src/context/GlobalNavContext.tsx +340 -0
  38. package/client/src/context/SelectionSourceContext.tsx +26 -0
  39. package/client/src/hooks/useCursorInput.ts +66 -24
  40. package/client/src/hooks/useDownloadedPieceVersions.ts +39 -0
  41. package/client/src/hooks/useGridColumns.ts +29 -0
  42. package/client/src/hooks/useInView.ts +32 -0
  43. package/client/src/hooks/usePiecePreview.ts +124 -0
  44. package/client/src/pages/Controls/index.tsx +126 -0
  45. package/client/src/pages/Game/index.tsx +11 -15
  46. package/client/src/pages/MatchMaking/index.tsx +6 -3
  47. package/client/src/pages/PreviewRoster/index.tsx +118 -0
  48. package/client/src/styles/global.css +355 -6
  49. package/client/src/utils/inputLabels.ts +25 -0
  50. package/client/test-results/.last-run.json +4 -0
  51. package/client/tsconfig.tsbuildinfo +1 -1
  52. package/dist/config/index.js +2 -0
  53. package/dist/config/index.js.map +1 -1
  54. package/dist/config/inputBindings.js +40 -0
  55. package/dist/config/inputBindings.js.map +1 -0
  56. package/dist/config/manage.js +1 -0
  57. package/dist/config/manage.js.map +1 -1
  58. package/dist/handle-room/version-1/game-launcher/binaries.js +36 -0
  59. package/dist/handle-room/version-1/game-launcher/binaries.js.map +1 -0
  60. package/dist/handle-room/version-1/game-launcher/listing.js +24 -0
  61. package/dist/handle-room/version-1/game-launcher/listing.js.map +1 -0
  62. package/dist/handle-room/version-1/game-launcher/preview.js +38 -0
  63. package/dist/handle-room/version-1/game-launcher/preview.js.map +1 -0
  64. package/dist/handle-room/version-1/game-launcher/process.js +52 -0
  65. package/dist/handle-room/version-1/game-launcher/process.js.map +1 -0
  66. package/dist/handle-room/version-1/game-launcher/router.js +32 -0
  67. package/dist/handle-room/version-1/game-launcher/router.js.map +1 -0
  68. package/dist/handle-room/version-1/game-launcher/settings.js +49 -0
  69. package/dist/handle-room/version-1/game-launcher/settings.js.map +1 -0
  70. package/dist/handle-room/version-1/game-launcher/shared.js +28 -0
  71. package/dist/handle-room/version-1/game-launcher/shared.js.map +1 -0
  72. package/dist/handle-room/version-1/game-launcher/start.js +76 -0
  73. package/dist/handle-room/version-1/game-launcher/start.js.map +1 -0
  74. package/dist/handle-room/version-1/game-launcher/version.js +63 -0
  75. package/dist/handle-room/version-1/game-launcher/version.js.map +1 -0
  76. package/dist/handle-room/version-1/globals/FolderDB/SQLFolderDB/ensurePieceExists.js +22 -9
  77. package/dist/handle-room/version-1/globals/FolderDB/SQLFolderDB/ensurePieceExists.js.map +1 -1
  78. package/dist/handle-room/version-1/globals/FolderDB/SQLFolderDB/schema.js +50 -1
  79. package/dist/handle-room/version-1/globals/FolderDB/SQLFolderDB/schema.js.map +1 -1
  80. package/dist/handle-room/version-1/index.js +15 -16
  81. package/dist/handle-room/version-1/index.js.map +1 -1
  82. package/dist/handle-room/version-1/input-bindings.js +22 -0
  83. package/dist/handle-room/version-1/input-bindings.js.map +1 -0
  84. package/dist/handle-room/version-1/room-handler-bridge/exchange-and-download-selections.js +2 -1
  85. package/dist/handle-room/version-1/room-handler-bridge/exchange-and-download-selections.js.map +1 -1
  86. package/dist/handle-room/version-1/room-handler-bridge/http-handler.js +1 -1
  87. package/dist/handle-room/version-1/room-handler-bridge/http-handler.js.map +1 -1
  88. package/dist/handle-room/version-1/room-handler-bridge/steps.js +2 -1
  89. package/dist/handle-room/version-1/room-handler-bridge/steps.js.map +1 -1
  90. package/dist/handle-room/version-1/room-handler-bridge/ws-handler.js +2 -2
  91. package/dist/handle-room/version-1/room-handler-bridge/ws-handler.js.map +1 -1
  92. package/dist/index.js +18 -4
  93. package/dist/index.js.map +1 -1
  94. package/dist/util-routers/file-system/env.js +3 -0
  95. package/dist/util-routers/file-system/env.js.map +1 -0
  96. package/dist/util-routers/file-system/index.js +31 -0
  97. package/dist/util-routers/file-system/index.js.map +1 -0
  98. package/dist/util-routers/file-system/list.js +50 -0
  99. package/dist/util-routers/file-system/list.js.map +1 -0
  100. package/dist/util-routers/file-system/resolve-within-root.js +18 -0
  101. package/dist/util-routers/file-system/resolve-within-root.js.map +1 -0
  102. package/dist/util-routers/file-system/roster-lock.js +56 -0
  103. package/dist/util-routers/file-system/roster-lock.js.map +1 -0
  104. package/dist/utils/pick-file.js +82 -0
  105. package/dist/utils/pick-file.js.map +1 -0
  106. package/dist/utils/pick-folder.js +84 -0
  107. package/dist/utils/pick-folder.js.map +1 -0
  108. package/package.json +9 -8
  109. package/src/config/index.ts +8 -3
  110. package/src/config/inputBindings.ts +56 -0
  111. package/src/config/manage.ts +7 -0
  112. package/src/handle-room/version-1/game-launcher/binaries.ts +52 -0
  113. package/src/handle-room/version-1/game-launcher/listing.ts +36 -0
  114. package/src/handle-room/version-1/game-launcher/preview.ts +54 -0
  115. package/src/handle-room/version-1/game-launcher/process.ts +75 -0
  116. package/src/handle-room/version-1/game-launcher/router.ts +42 -0
  117. package/src/handle-room/version-1/game-launcher/settings.ts +58 -0
  118. package/src/handle-room/version-1/game-launcher/shared.ts +34 -0
  119. package/src/handle-room/version-1/game-launcher/start.ts +113 -0
  120. package/src/handle-room/version-1/game-launcher/version.ts +85 -0
  121. package/src/handle-room/version-1/globals/FolderDB/SQLFolderDB/ensurePieceExists.ts +39 -14
  122. package/src/handle-room/version-1/globals/FolderDB/SQLFolderDB/schema.ts +83 -1
  123. package/src/handle-room/version-1/globals/FolderDB/types.ts +24 -0
  124. package/src/handle-room/version-1/globals/types.ts +24 -2
  125. package/src/handle-room/version-1/index.ts +27 -26
  126. package/src/handle-room/version-1/input-bindings.ts +19 -0
  127. package/src/handle-room/version-1/room-handler-bridge/exchange-and-download-selections.ts +4 -1
  128. package/src/handle-room/version-1/room-handler-bridge/http-handler.ts +4 -1
  129. package/src/handle-room/version-1/room-handler-bridge/steps.ts +8 -0
  130. package/src/handle-room/version-1/room-handler-bridge/ws-handler.ts +2 -2
  131. package/src/index.ts +42 -10
  132. package/src/util-routers/file-system/env.ts +7 -0
  133. package/src/util-routers/file-system/index.ts +23 -0
  134. package/src/util-routers/file-system/list.ts +62 -0
  135. package/src/util-routers/file-system/resolve-within-root.ts +25 -0
  136. package/src/util-routers/file-system/roster-lock.ts +74 -0
  137. package/src/utils/pick-file.ts +81 -0
  138. package/src/utils/pick-folder.ts +92 -0
  139. package/tests/integration/filesystem.test.ts +117 -0
  140. package/tests/integration/game-launcher-binaries.test.ts +263 -0
  141. package/tests/integration/game-launcher-game-complete.test.ts +111 -0
  142. package/tests/integration/game-launcher-preview.test.ts +107 -0
  143. package/tests/integration/game-launcher-settings.test.ts +123 -8
  144. package/tests/integration/game-processes-ws.test.ts +122 -0
  145. package/tests/integration/helpers/fakeFolderDB.ts +16 -0
  146. package/tests/integration/helpers/fakePluginRuntime.ts +10 -1
  147. package/tests/integration/helpers/server.ts +23 -3
  148. package/tests/integration/input-bindings.test.ts +94 -0
  149. package/tests/integration/piece-files.test.ts +1 -1
  150. package/tests/integration/roster-lock.test.ts +86 -0
  151. package/vitest.config.ts +7 -1
  152. package/client/dist/assets/index-CX6eCHuc.js +0 -125
  153. package/client/dist/assets/index-gxAuIfGQ.css +0 -1
  154. package/client/node_modules/.vite/deps/chunk-EDVVVQBR.js.map +0 -7
  155. package/dist/handle-room/version-1/game-launcher.js +0 -197
  156. package/dist/handle-room/version-1/game-launcher.js.map +0 -1
  157. package/src/handle-room/version-1/game-launcher.ts +0 -287
@@ -0,0 +1,85 @@
1
+ import z from "zod";
2
+ import { jsonBody, HTTPRequestHandler, HTTPError } from "../../../utils/http-router";
3
+ import { V1Env } from "../globals/types";
4
+ import { castLockConfig } from "../piece-sort";
5
+ import { requirePluginName, requireBinaryLocation, resolveTarget } from "./shared";
6
+
7
+ export const getGameLauncherVersion: HTTPRequestHandler = async function(
8
+ this: V1Env, { res }, routeInfo
9
+ ){
10
+ const pluginName = requirePluginName(routeInfo);
11
+ const binaryLocation = await requireBinaryLocation(this, pluginName);
12
+ const target = resolveTarget(routeInfo);
13
+
14
+ const [local, supported] = await Promise.all([
15
+ this.pluginRuntime.gameLauncher.getLocalVersion(pluginName, binaryLocation, target),
16
+ this.pluginRuntime.gameLauncher.getSupportedVersion(pluginName, binaryLocation),
17
+ ]);
18
+
19
+ res.writeHead(200, { "Content-Type": "application/json" });
20
+ res.end(JSON.stringify({ local, supported }));
21
+ }
22
+
23
+ export const validateGameLauncherBinaryLocation: HTTPRequestHandler = async function(
24
+ this: V1Env, { res }, routeInfo
25
+ ){
26
+ const pluginName = requirePluginName(routeInfo);
27
+ const binaryLocation = await requireBinaryLocation(this, pluginName);
28
+ const target = resolveTarget(routeInfo);
29
+
30
+ const result = await this.pluginRuntime.gameLauncher.validateBinaryLocation(pluginName, binaryLocation, target);
31
+
32
+ res.writeHead(200, { "Content-Type": "application/json" });
33
+ res.end(JSON.stringify(result));
34
+ }
35
+
36
+ const validateGameConfigBodySchema = z.object({
37
+ gameConfig: z.unknown(),
38
+ rosterConfig: z.unknown(),
39
+ }).strict();
40
+
41
+ // No binaryLocation involved (unlike every other route in this file) - this is
42
+ // a pre-room-creation check, not a local-machine one, so it's callable before
43
+ // a binaryLocation is even configured.
44
+ export const validateGameLauncherGameConfig: HTTPRequestHandler = async function(
45
+ this: V1Env, { req, res }, routeInfo
46
+ ){
47
+ const pluginName = requirePluginName(routeInfo);
48
+ const body = await jsonBody(req);
49
+ const parseResult = validateGameConfigBodySchema.safeParse(body);
50
+ if(!parseResult.success) throw new HTTPError(400, "Bad Form", parseResult.error);
51
+ const rosterConfig = castLockConfig(parseResult.data.rosterConfig);
52
+
53
+ const problems = await this.pluginRuntime.gameLauncher.validateGameConfig(
54
+ pluginName, parseResult.data.gameConfig, rosterConfig
55
+ );
56
+
57
+ res.writeHead(200, { "Content-Type": "application/json" });
58
+ res.end(JSON.stringify({ problems }));
59
+ }
60
+
61
+ // Deliberately doesn't call requireBinaryLocation like every other route in
62
+ // this file - getBinary *acquires* a binaryLocation rather than operating
63
+ // on an already-configured one (see GameLauncherPlugin.getBinary), so a
64
+ // plugin that supports it can be downloaded before any binaryLocation has
65
+ // ever been set, not just updated once one already is.
66
+ export const updateGameLauncherBinary: HTTPRequestHandler = async function(
67
+ this: V1Env, { res }, routeInfo
68
+ ){
69
+ const pluginName = requirePluginName(routeInfo);
70
+ const target = resolveTarget(routeInfo);
71
+
72
+ let binaryLocation: string;
73
+ try {
74
+ ({ binaryLocation } = await this.pluginRuntime.gameLauncher.getBinary(pluginName, target));
75
+ } catch(e){
76
+ // getBinary throws a plain Error when a plugin doesn't declare one at
77
+ // all (see GameLauncher.getBinary) - that's a client-facing 400 ("this
78
+ // runner can't be downloaded in-app"), not a server fault.
79
+ throw new HTTPError(400, (e as Error).message);
80
+ }
81
+ await this.fileDB.recordBinaryDownloaded(pluginName, binaryLocation);
82
+
83
+ res.writeHead(200, { "Content-Type": "application/json" });
84
+ res.end(JSON.stringify({ ok: true, binaryLocation }));
85
+ }
@@ -118,19 +118,50 @@ export class SQLite3FolderDB implements IFolderDB {
118
118
  };
119
119
  }
120
120
 
121
+ async recordBinaryDownloaded(pluginName: string, binaryLocation: string): Promise<void> {
122
+ this.db.recordBinaryDownloaded(pluginName, binaryLocation);
123
+ }
124
+
125
+ async recordBinaryUsed(pluginName: string, binaryLocation: string): Promise<void> {
126
+ this.db.recordBinaryUsed(pluginName, binaryLocation);
127
+ }
128
+
129
+ async getBinaryUsageFor(
130
+ pluginName: string, binaryLocations: Array<string>
131
+ ): Promise<Map<string, { downloadedAt: number, lastUsedAt: number | null }>> {
132
+ return this.db.getBinaryUsageFor(pluginName, binaryLocations);
133
+ }
134
+
135
+ async removeBinaryUsage(pluginName: string, binaryLocation: string): Promise<void> {
136
+ this.db.removeBinaryUsage(pluginName, binaryLocation);
137
+ }
138
+
139
+ private resolveCompleteFolder(
140
+ engineConfig: RosterLockV1Config["engine"],
141
+ pieceType: string,
142
+ piece: Pick<RosterLockPiece, "version" | "pathVariables">,
143
+ ): string {
144
+ const state = this.db.getPieceState(pieceIndexOf(engineConfig, pieceType, piece));
145
+ if(!state) throw new HTTPError(404, "Piece doesn't exist");
146
+ if(state.status !== "complete") throw new HTTPError(409, "Piece not finished");
147
+ return this.pieceFolder(engineConfig, pieceType, state.folderName);
148
+ }
149
+
150
+ async getPieceFolder(
151
+ engineConfig: RosterLockV1Config["engine"],
152
+ pieceType: string,
153
+ piece: Pick<RosterLockPiece, "version" | "pathVariables">,
154
+ ): Promise<string> {
155
+ return this.resolveCompleteFolder(engineConfig, pieceType, piece);
156
+ }
157
+
121
158
  async* getFilesofAsset(
122
159
  engineConfig: RosterLockV1Config["engine"],
123
160
  pieceType: string,
124
161
  piece: Pick<RosterLockPiece, "version" | "pathVariables">,
125
162
  assetName: string
126
163
  ): AsyncIterable<string>{
127
- const state = this.db.getPieceState(pieceIndexOf(engineConfig, pieceType, piece));
128
- if(!state) throw new HTTPError(404, "Piece Doesn't exist");
129
- if(state.status !== "complete")
130
- throw new HTTPError(409, "Piece not finished");
131
- const folder = this.pieceFolder(
132
- engineConfig, pieceType, state.folderName
133
- );
164
+ const folder = this.resolveCompleteFolder(engineConfig, pieceType, piece);
134
165
  for await (const path of getFilesFromFolder(folder)){
135
166
  const assets = getMatchingAssetsForFile(
136
167
  engineConfig.pieceDefinitions[pieceType],
@@ -148,13 +179,7 @@ export class SQLite3FolderDB implements IFolderDB {
148
179
  piece: Pick<RosterLockPiece, "version" | "pathVariables">,
149
180
  filePath: string
150
181
  ): Promise<Readable> {
151
- const state = this.db.getPieceState(pieceIndexOf(engineConfig, pieceType, piece));
152
- if(!state) throw new HTTPError(404, "Piece doesn't exist");
153
- if(state.status !== "complete")
154
- throw new HTTPError(409, "Piece not finished");
155
- const folder = this.pieceFolder(
156
- engineConfig, pieceType, state.folderName
157
- );
182
+ const folder = this.resolveCompleteFolder(engineConfig, pieceType, piece);
158
183
  const fullPath = pathJoin(folder, filePath);
159
184
  const rel = pathRelative(folder, fullPath)
160
185
  if(rel.startsWith("..") || isAbsolutePath(rel))
@@ -99,6 +99,23 @@ CREATE TABLE IF NOT EXISTS download_sources (
99
99
  FOREIGN KEY (engine_name, piece_type, logic_hash, media_hash)
100
100
  REFERENCES pieces(engine_name, piece_type, logic_hash, media_hash)
101
101
  );
102
+
103
+ -- "downloaded at"/"last used at" for a game-launcher binary
104
+ -- (plugin-runtime's GameLauncher.getBinary/listBinaries - see
105
+ -- docs/v2/binary-location.md) - neither is something a plugin itself could
106
+ -- report (getLocalVersion reads what's actually installed, not when
107
+ -- match-agent fetched or last ran it), so this is match-agent's own
108
+ -- bookkeeping, sharing this same database file rather than a second one
109
+ -- just for this. One row per binaryLocation GameLauncher.getBinary has
110
+ -- ever produced; removeGameLauncherBinary deletes the row along with the
111
+ -- folder it describes.
112
+ CREATE TABLE IF NOT EXISTS game_launcher_binaries (
113
+ plugin_name TEXT NOT NULL,
114
+ binary_location TEXT NOT NULL,
115
+ downloaded_at INTEGER NOT NULL DEFAULT (unixepoch()),
116
+ last_used_at INTEGER,
117
+ PRIMARY KEY (plugin_name, binary_location)
118
+ );
102
119
  `;
103
120
 
104
121
  const PIECE_WHERE = `
@@ -442,7 +459,72 @@ export function prepareDatabase(dbLocation: string){
442
459
  return parsePieceRow(piece, sourcesByPiece.get(key) ?? []);
443
460
  }),
444
461
  };
445
- }
462
+ },
463
+
464
+ // Called right after a successful GameLauncher.getBinary - "downloaded
465
+ // at" always wins on conflict (re-downloading the same binaryLocation,
466
+ // which getBinary's own tag-named subfolders make unlikely but not
467
+ // impossible, is still a fresh download).
468
+ recordBinaryDownloaded(pluginName: string, binaryLocation: string){
469
+ db.prepare(
470
+ `INSERT INTO game_launcher_binaries (plugin_name, binary_location, downloaded_at)
471
+ VALUES (@pluginName, @binaryLocation, unixepoch())
472
+ ON CONFLICT (plugin_name, binary_location) DO UPDATE SET downloaded_at = excluded.downloaded_at`
473
+ ).run({ pluginName, binaryLocation });
474
+ },
475
+
476
+ // Called right after a successful GameLauncher.startGame. Inserts a row
477
+ // even for a binaryLocation getBinary never produced (a manually
478
+ // configured one) - harmless (listGameLauncherBinaries only ever joins
479
+ // this against GameLauncher.listBinaries' own dataDir enumeration, so a
480
+ // stray row for an external path is just never surfaced), and simpler
481
+ // than having this route ask plugin-runtime "is this one of yours"
482
+ // first.
483
+ recordBinaryUsed(pluginName: string, binaryLocation: string){
484
+ db.prepare(
485
+ `INSERT INTO game_launcher_binaries (plugin_name, binary_location, downloaded_at, last_used_at)
486
+ VALUES (@pluginName, @binaryLocation, unixepoch(), unixepoch())
487
+ ON CONFLICT (plugin_name, binary_location) DO UPDATE SET last_used_at = excluded.last_used_at`
488
+ ).run({ pluginName, binaryLocation });
489
+ },
490
+
491
+ // Batched (one query, not one per listed binary) - keyed by
492
+ // binaryLocation so listGameLauncherBinaries can merge this onto
493
+ // GameLauncher.listBinaries' own result by matching path.
494
+ getBinaryUsageFor(
495
+ pluginName: string, binaryLocations: Array<string>
496
+ ): Map<string, { downloadedAt: number, lastUsedAt: number | null }> {
497
+ const result = new Map<string, { downloadedAt: number, lastUsedAt: number | null }>();
498
+ if(binaryLocations.length === 0) return result;
499
+ const params: Record<string, string> = { pluginName };
500
+ const placeholders = binaryLocations.map((location, i) => {
501
+ params[`loc${i}`] = location;
502
+ return `@loc${i}`;
503
+ }).join(", ");
504
+ const rows = db.prepare(
505
+ `SELECT binary_location, downloaded_at, last_used_at FROM game_launcher_binaries
506
+ WHERE plugin_name = @pluginName AND binary_location IN (${placeholders})`
507
+ ).all(params) as Array<{ binary_location: string, downloaded_at: number, last_used_at: number | null }>;
508
+ for(const row of rows){
509
+ // unixepoch() stores seconds - converted to ms here, same
510
+ // convention StoredPieceListing's completedAt already uses, so
511
+ // nothing downstream has to know this table's own on-disk units.
512
+ result.set(row.binary_location, {
513
+ downloadedAt: row.downloaded_at * 1000,
514
+ lastUsedAt: row.last_used_at === null ? null : row.last_used_at * 1000,
515
+ });
516
+ }
517
+ return result;
518
+ },
519
+
520
+ // Called alongside GameLauncher.removeBinary, which deletes the folder
521
+ // itself - this just drops the bookkeeping row so it doesn't outlive
522
+ // what it describes.
523
+ removeBinaryUsage(pluginName: string, binaryLocation: string){
524
+ db.prepare(
525
+ `DELETE FROM game_launcher_binaries WHERE plugin_name = @pluginName AND binary_location = @binaryLocation`
526
+ ).run({ pluginName, binaryLocation });
527
+ },
446
528
  }
447
529
  }
448
530
 
@@ -53,6 +53,15 @@ export interface IFolderDB {
53
53
  selectedPiece: Pick<RosterLockPiece, "version" | "pathVariables">,
54
54
  filePath: string
55
55
  ): Promise<Readable>
56
+ // Resolves a completed download's real on-disk folder - throws the same
57
+ // 404 ("doesn't exist")/409 ("not finished") HTTPErrors as getFilesofAsset/
58
+ // getPieceFileContents rather than returning undefined, so callers use the
59
+ // same try/catch shape for all three.
60
+ getPieceFolder(
61
+ engineConfig: RosterLockV1Config["engine"],
62
+ pieceType: string,
63
+ selectedPiece: Pick<RosterLockPiece, "version" | "pathVariables">,
64
+ ): Promise<string>
56
65
  listPieces(
57
66
  engineName: string,
58
67
  pieceType: string,
@@ -68,5 +77,20 @@ export interface IFolderDB {
68
77
  page: number,
69
78
  limit: number,
70
79
  }): Promise<StoredPieceListing>
80
+
81
+ // "Downloaded at"/"last used at" for a game-launcher binary (see
82
+ // SQLFolderDB/schema.ts's game_launcher_binaries table) - sharing this
83
+ // same database rather than a second one just for game-launcher
84
+ // bookkeeping, even though it isn't piece-shaped. Neither timestamp is
85
+ // something a plugin could ever report itself (GameLauncher.listBinaries
86
+ // reads what's actually installed via getLocalVersion, not when/whether
87
+ // match-agent fetched or ran it), so this is match-agent's own
88
+ // responsibility to track and merge in.
89
+ recordBinaryDownloaded(pluginName: string, binaryLocation: string): Promise<void>,
90
+ recordBinaryUsed(pluginName: string, binaryLocation: string): Promise<void>,
91
+ getBinaryUsageFor(
92
+ pluginName: string, binaryLocations: Array<string>
93
+ ): Promise<Map<string, { downloadedAt: number, lastUsedAt: number | null }>>,
94
+ removeBinaryUsage(pluginName: string, binaryLocation: string): Promise<void>,
71
95
  }
72
96
 
@@ -1,7 +1,8 @@
1
1
 
2
+ import { EventEmitter } from "node:events";
2
3
  import { IFolderDB } from "./FolderDB";
3
4
  import { PluginManager } from "@roster-lock/plugin-runtime";
4
- import { GameProcessHandle } from "@roster-lock/types";
5
+ import { GameProcessHandle, HandleFullSelectionArg } from "@roster-lock/types";
5
6
 
6
7
  // Known upfront (CLI --port) rather than read off a listening socket, so it's
7
8
  // a plain value in the common case - getPort() only needs to be lazy for
@@ -14,18 +15,39 @@ export type MatchAgentSelfInfo = {
14
15
 
15
16
  // pluginName is kept alongside the handle (not just the handleId key) so a
16
17
  // process can be listed/identified without a caller having to already know
17
- // which plugin started it - see game-launcher.ts's listGameProcesses.
18
+ // which plugin started it - see game-launcher/process.ts's listGameProcesses.
18
19
  export type ProcessHandleEntry = {
19
20
  pluginName: string,
20
21
  handle: GameProcessHandle,
21
22
  }
22
23
 
24
+ // What bindStepsToBridge already computes once a room's selection protocol
25
+ // finishes (steps.ts) - saved here, keyed by relayRoomId, so the later,
26
+ // separate game-launch request (game-launcher/start.ts's startGameLauncher, which
27
+ // has no other way to recover this) can hand it to piece-selection-sort's
28
+ // handleGameComplete once a plugin reports a winner. In-memory only, same
29
+ // best-effort tradeoff as processHandles - an entry for a room whose game
30
+ // never reports a result just outlives its usefulness until a restart.
31
+ export type GameCompletionContext = Omit<HandleFullSelectionArg, "dataDir">;
32
+
23
33
  export type V1Env = {
24
34
  fileDB: IFolderDB,
25
35
  pluginRuntime: PluginManager,
26
36
  matchAgent: MatchAgentSelfInfo,
37
+ // The same config file findConfigFile() resolved at startup (see
38
+ // ../../../config/findFile.ts) - carried here so routes can read/write
39
+ // sibling files that should travel with it (e.g. input-bindings.ts),
40
+ // without each one re-deriving where match-agent's portable root is.
41
+ configFilePath: string,
27
42
  // In-memory only - a match-agent restart loses track of processes it
28
43
  // started before the restart (same best-effort tradeoff as GameProcessHandle
29
44
  // itself; there's no persistent process-supervision story here).
30
45
  processHandles: Map<string, ProcessHandleEntry>,
46
+ gameCompletionContext: Map<string, GameCompletionContext>,
47
+ // Fires "changed" whenever processHandles gains an entry or one of its
48
+ // handles reports exit/crash - what game-launcher/process.ts's gameProcessesWs
49
+ // listens on to push a fresh listGameProcesses-shaped snapshot, so a
50
+ // client can watch process status live instead of polling
51
+ // /game-launcher/processes.
52
+ processEvents: EventEmitter,
31
53
  }
@@ -1,3 +1,4 @@
1
+ import { EventEmitter } from "node:events";
1
2
  import { HTTPRouter } from "../../utils/http-router";
2
3
  import { WebSocketRouter } from "../../utils/websocket-router";
3
4
 
@@ -7,17 +8,21 @@ import { httpHandler } from "./room-handler-bridge/http-handler";
7
8
  import { getFilesOfAsset, getPieceFileContents } from "./file-routes";
8
9
  import { ensurePieceDownloaded, ensurePieceDownloadedWs, listDownloadedPiecesDirect } from "./select";
9
10
  import { listAvailableSortPlugins, sortListPlugin, gameComplete } from "./piece-sort";
10
- import {
11
- listAvailableGameLaunchers, getGameLauncherSettings, setGameLauncherSettings, getGameLauncherVersion,
12
- validateGameLauncherBinaryLocation, validateGameLauncherGameConfig, updateGameLauncherBinary, startGameLauncher,
13
- getGameProcessStatus, installGameLauncherPlugin, listGameProcesses, stopGameProcess,
14
- } from "./game-launcher";
15
- import { IFolderDB, V1Env, MatchAgentSelfInfo, ProcessHandleEntry } from "./globals";
11
+ import { createGameLauncherRouter } from "./game-launcher/router";
12
+ import { gameProcessesWs } from "./game-launcher/process";
13
+ import { getInputBindingsRoute, setInputBindingsRoute } from "./input-bindings";
14
+ import { IFolderDB, V1Env, MatchAgentSelfInfo, ProcessHandleEntry, GameCompletionContext } from "./globals";
16
15
  import { PluginManager } from "@roster-lock/plugin-runtime";
17
16
 
18
- export const createV1Routers = (fileDB: IFolderDB, pluginRuntime: PluginManager, matchAgent: MatchAgentSelfInfo)=>{
17
+ export const createV1Routers = (
18
+ fileDB: IFolderDB, pluginRuntime: PluginManager, matchAgent: MatchAgentSelfInfo, configFilePath: string
19
+ )=>{
19
20
  const processHandles = new Map<string, ProcessHandleEntry>();
20
- const env: V1Env = { fileDB, pluginRuntime, matchAgent, processHandles };
21
+ const gameCompletionContext = new Map<string, GameCompletionContext>();
22
+ const processEvents = new EventEmitter();
23
+ const env: V1Env = {
24
+ fileDB, pluginRuntime, matchAgent, configFilePath, processHandles, gameCompletionContext, processEvents,
25
+ };
21
26
  const httpRouter = new HTTPRouter();
22
27
  const wsRouter = new WebSocketRouter()
23
28
 
@@ -29,26 +34,22 @@ export const createV1Routers = (fileDB: IFolderDB, pluginRuntime: PluginManager,
29
34
  httpRouter.get("/piece/sort-list/available", listAvailableSortPlugins.bind(env));
30
35
  httpRouter.post("/piece/sort-list/plugin/:pluginName", sortListPlugin.bind(env));
31
36
  httpRouter.post("/game-complete", gameComplete.bind(env));
32
- httpRouter.get("/game-launcher/available", listAvailableGameLaunchers.bind(env));
33
- httpRouter.post("/game-launcher/:pluginName/install", installGameLauncherPlugin.bind(env));
34
- httpRouter.get("/game-launcher/:pluginName/settings", getGameLauncherSettings.bind(env));
35
- httpRouter.put("/game-launcher/:pluginName/settings", setGameLauncherSettings.bind(env));
36
- httpRouter.get("/game-launcher/:pluginName/version", getGameLauncherVersion.bind(env));
37
- httpRouter.get("/game-launcher/:pluginName/validate", validateGameLauncherBinaryLocation.bind(env));
38
- httpRouter.post("/game-launcher/:pluginName/validate-game-config", validateGameLauncherGameConfig.bind(env));
39
- httpRouter.post("/game-launcher/:pluginName/update", updateGameLauncherBinary.bind(env));
40
- httpRouter.post("/game-launcher/:pluginName/start", startGameLauncher.bind(env));
41
- httpRouter.get("/game-launcher/:pluginName/process/:handleId", getGameProcessStatus.bind(env));
42
- httpRouter.post("/game-launcher/:pluginName/process/:handleId/stop", stopGameProcess.bind(env));
43
- // Plugin-agnostic, unlike the routes above - lists every process this
44
- // match-agent has started across every plugin (see pages/Game in
45
- // match-agent-client), not just one plugin's.
46
- httpRouter.get("/game-launcher/processes", listGameProcesses.bind(env));
47
-
37
+ httpRouter.get("/input-bindings", getInputBindingsRoute.bind(env));
38
+ httpRouter.put("/input-bindings", setInputBindingsRoute.bind(env));
39
+ httpRouter.use("/game-launcher", createGameLauncherRouter(env));
48
40
 
49
41
  wsRouter.mount("/sync-dl", wsHandler.bind(env));
50
42
  wsRouter.mount("/piece/ensure", ensurePieceDownloadedWs.bind(env));
51
-
52
- return { httpRouter, wsRouter };
43
+ // WS counterpart to /game-launcher/processes above - pushes the same
44
+ // listGameProcesses snapshot on every connect and again whenever it
45
+ // changes, so a client (e.g. match-agent-client's Game page) doesn't have
46
+ // to poll the HTTP route for status.
47
+ wsRouter.mount("/game-launcher/processes", gameProcessesWs.bind(env));
48
+
49
+ // env is returned alongside the routers (not just used to bind them) so a
50
+ // caller - e.g. a test - can seed/inspect in-memory state like
51
+ // gameCompletionContext directly, without needing a real relay server to
52
+ // drive the room negotiation that would otherwise populate it.
53
+ return { httpRouter, wsRouter, env };
53
54
  }
54
55
 
@@ -0,0 +1,19 @@
1
+ import { jsonBody, HTTPRequestHandler, HTTPError } from "../../utils/http-router";
2
+ import { getInputBindings, setInputBindings, inputBindingsSchema } from "../../config/inputBindings";
3
+ import { V1Env } from "./globals/types";
4
+
5
+ export const getInputBindingsRoute: HTTPRequestHandler = async function(this: V1Env, { res }){
6
+ const bindings = await getInputBindings(this.configFilePath);
7
+ res.writeHead(200, { "Content-Type": "application/json" });
8
+ res.end(JSON.stringify(bindings));
9
+ }
10
+
11
+ export const setInputBindingsRoute: HTTPRequestHandler = async function(this: V1Env, { req, res }){
12
+ const body = await jsonBody(req);
13
+ const parsed = inputBindingsSchema.safeParse(body);
14
+ if(!parsed.success) throw new HTTPError(400, "Bad Form", parsed.error);
15
+
16
+ await setInputBindings(this.configFilePath, parsed.data);
17
+ res.writeHead(200, { "Content-Type": "application/json" });
18
+ res.end(JSON.stringify({ ok: true }));
19
+ }
@@ -6,6 +6,7 @@ import { RosterLockV1Config, RosterLockV1SyncDLRequestClientToAgent } from "@ros
6
6
  import { ROSTERLOCK_V1_CASTER_JSONSCHEMA } from "@roster-lock/shared";
7
7
  import { UserSelectionSchema } from "../schema/selected";
8
8
  import { IFolderDB } from "../globals/FolderDB";
9
+ import { GameCompletionContext } from "../globals/types";
9
10
  import { once } from "events";
10
11
  import z, { ZodType } from "zod";
11
12
  import { PluginManager } from "@roster-lock/plugin-runtime";
@@ -52,7 +53,8 @@ export async function exchangeAndDownloadSelections(
52
53
  fileDB: IFolderDB,
53
54
  pluginRuntime: PluginManager,
54
55
  roomRequest: RosterLockV1SyncDLRequestClientToAgent,
55
- progressListeners: ProgressListeners = {}
56
+ progressListeners: ProgressListeners = {},
57
+ onGameComplete?: (relayRoomId: string, ctx: GameCompletionContext) => void,
56
58
  ){
57
59
  const roomURL = prepareRelayURL(roomRequest);
58
60
 
@@ -88,6 +90,7 @@ export async function exchangeAndDownloadSelections(
88
90
  ownSelections: roomRequest.playerSelections,
89
91
  lockConfig: roomRequest.rosterConfig,
90
92
  gameControlledSelections: {},
93
+ onGameComplete: onGameComplete && ((ctx)=>onGameComplete(roomRequest.relay.roomId, ctx)),
91
94
  }, progressListeners);
92
95
 
93
96
  // The relay closes the room websocket with a close reason as soon as it fails
@@ -7,7 +7,10 @@ export const httpHandler: HTTPRequestHandler = async function(this: V1Env, { req
7
7
  try {
8
8
  const body = await jsonBody(req);
9
9
  const roomRequest = castRoomRequest(body);
10
- const results = await exchangeAndDownloadSelections(this.fileDB, this.pluginRuntime, roomRequest);
10
+ const results = await exchangeAndDownloadSelections(
11
+ this.fileDB, this.pluginRuntime, roomRequest, undefined,
12
+ (relayRoomId, ctx)=>{ this.gameCompletionContext.set(relayRoomId, ctx); },
13
+ );
11
14
  res.writeHead(200, { "Content-Type": "application/json" });
12
15
  res.end(JSON.stringify(results));
13
16
  }catch(e){
@@ -12,6 +12,7 @@ import { UserSelectionSchema } from "../schema/selected";
12
12
  import { PluginManager } from "@roster-lock/plugin-runtime";
13
13
  import { handleDownloads } from "../handleDownloads";
14
14
  import { IFolderDB } from "../globals/FolderDB";
15
+ import { GameCompletionContext } from "../globals/types";
15
16
  import { RosterLockDownloadUpdate } from "@roster-lock/types";
16
17
 
17
18
  type MachinePublicKey = string;
@@ -39,6 +40,11 @@ type RoomArgs = {
39
40
  ownSelections: Record<number, UserSelection>,
40
41
  lockConfig: RosterLockV1Config,
41
42
  gameControlledSelections: Record<string, Array<SelectedPiece> | Record<PlayerId, Array<SelectedPiece>>>,
43
+ // Lets a caller stash this room's {lockConfig, localUsers, userSelections}
44
+ // for later reuse once a game started from this room reports a result -
45
+ // see game-launcher/start.ts's gameEnded handler, which has no other way to
46
+ // recover this (it's a separate request cycle from this one entirely).
47
+ onGameComplete?: (ctx: GameCompletionContext) => void,
42
48
  }
43
49
 
44
50
  export type ProgressListeners = Partial<{
@@ -68,6 +74,7 @@ export function bindStepsToBridge(
68
74
  ownSelections,
69
75
  lockConfig,
70
76
  gameControlledSelections,
77
+ onGameComplete,
71
78
  }: RoomArgs,
72
79
  progressListeners: ProgressListeners = {}
73
80
  ): Promise<RosterLockV1SyncDLResult>{
@@ -199,6 +206,7 @@ export function bindStepsToBridge(
199
206
  Object.entries(decryptedSelections).map(([playerId, input])=>[playerId, input.userSelection])
200
207
  );
201
208
  const localPlayers = Object.keys(ownSelections).map((index)=>`${ownMachinePublicKey}:${index}`);
209
+ onGameComplete?.({ lockConfig, localUsers: localPlayers, userSelections });
202
210
  return pluginRuntime.pieceSort.handleFullSelection({ lockConfig, localUsers: localPlayers, userSelections });
203
211
  }).catch((e)=>{
204
212
  console.error("piece-selection-sort handleFullSelection failed", e);
@@ -8,7 +8,7 @@ import { V1Env } from "../globals/types";
8
8
  export const wsHandler: WebSocketHandlerCallback = async function(
9
9
  this: V1Env, { ws: gameWebSocket }, params, next
10
10
  ){
11
- const { fileDB, pluginRuntime } = this;
11
+ const { fileDB, pluginRuntime, gameCompletionContext } = this;
12
12
  try {
13
13
  const gameBridge = new MessageBridge((message)=>gameWebSocket.send(JSON.stringify(message)));
14
14
  gameWebSocket.on("message", (message)=>{
@@ -19,7 +19,7 @@ export const wsHandler: WebSocketHandlerCallback = async function(
19
19
  return await exchangeAndDownloadSelections(fileDB, pluginRuntime, roomRequest, {
20
20
  onState: (state)=>{gameBridge.sendEvent("room-state", state)},
21
21
  onDownloadProgress: (event)=>{gameBridge.sendEvent("download-progress", event)},
22
- });
22
+ }, (relayRoomId, ctx)=>{ gameCompletionContext.set(relayRoomId, ctx); });
23
23
  });
24
24
  gameBridge.sendEvent("ready", {});
25
25
  }catch(e){