Public: anyone can read this; the crew can change it.
Game door: one Talk engine for game chat, web and iOS (#18247) #18316
Merged 4h 28m ago, live in production
scout/forge:scout/18310-game-door-one-talk-engine-for-game-chat → main 0 commits fork 4 threads · 4 unresolved
6 files
changed +326
−106
src/actions/talk_door.ts added +63
| @@ -0,0 +1,63 @@ | ||
| 1 | /** | |
| 2 | * What a door that keeps its own conversation asks of Talk (#18310): the game door's chat, and any | |
| 3 | * door after it. One place makes or finds the person's conversation, limits it to the door's tools, | |
| 4 | * sends the words through `talk` (so the throttle, the agent switch and the turn are Talk's, not a | |
| 5 | * copy), raises a held action in it, and reads back what is still held there. Which conversation a | |
| 6 | * door keeps for whom is the door's own row; this module only takes it and gives it back. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { limitToGame } from "../core/conversation_door.ts"; | |
| 12 | import { appendTurn, createConversation, getConversation } from "../core/conversations.ts"; | |
| 13 | import { hold, waitingFor } from "../core/fence.ts"; | |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | import type { Said } from "../crew/conversation.ts"; | |
| 16 | import { confirmSentence } from "../crew/conversation_ask.ts"; | |
| 17 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 18 | import { waitingConfirms, type Waiting } from "./conversation_confirms.ts"; | |
| 19 | import { talk, type TalkRefusal } from "./talk.ts"; | |
| 20 | ||
| 21 | /** The conversation to use: `kept` while it is there, else a new one limited to the game door. */ | |
| 22 | export function conversationIn(db: Database, userId: string, kept?: string): Result<{ id: string; gone: boolean }, "too_many"> { | |
| 23 | if (kept !== undefined && getConversation(db, userId, kept) !== undefined) return ok({ id: kept, gone: false }); | |
| 24 | const made = createConversation(db, userId); | |
| 25 | if (!made.ok) return err("too_many"); | |
| 26 | limitToGame(db, made.value.id); | |
| 27 | return ok({ id: made.value.id, gone: kept !== undefined }); | |
| 28 | } | |
| 29 | ||
| 30 | /** | |
| 31 | * What was asked: the conversation it went to, whether the kept one was gone, and Talk's receipt. | |
| 32 | */ | |
| 33 | export interface Asked { | |
| 34 | readonly conversation: string; | |
| 35 | readonly gone: boolean; | |
| 36 | readonly said: Said; | |
| 37 | } | |
| 38 | ||
| 39 | /** Words typed at a door, sent to the crew in the person's conversation for that door. */ | |
| 40 | export function askThrough(app: App, user: User, words: string, kept?: string): Result<Asked, TalkRefusal | "too_many"> { | |
| 41 | const found = conversationIn(app.db, user.id, kept); | |
| 42 | if (!found.ok) return found; | |
| 43 | const said = talk(app, user, words, [], "inject", found.value.id); | |
| 44 | return said.ok ? ok({ conversation: found.value.id, gone: found.value.gone, said: said.value }) : said; | |
| 45 | } | |
| 46 | ||
| 47 | /** A held action raised in `conversation`, with its sentence shown there with its buttons. */ | |
| 48 | export function raiseHeld(db: Database, userId: string, conversation: string, tool: string, args: Record<string, unknown>, now = Date.now()): Result<{ confirm: string; does: string }, "too_many_waiting"> { | |
| 49 | const confirm = hold(db, `conversation:${conversation}`, userId, tool, args, now); | |
| 50 | if (confirm === null) return err("too_many_waiting"); | |
| 51 | const does = confirmSentence(tool, args); | |
| 52 | appendTurn(db, userId, conversation, { role: "confirm", text: JSON.stringify({ confirm, tool, does }) }); | |
| 53 | return ok({ confirm, does }); | |
| 54 | } | |
| 55 | ||
| 56 | /** | |
| 57 | * The person's confirms still waiting in `conversation`, oldest first: answered on the page or the | |
| 58 | * API. | |
| 59 | */ | |
| 60 | export function heldIn(app: App, user: User, conversation: string, now = Date.now()): Waiting[] { | |
| 61 | const here = new Set(waitingFor(app.db, user.id, now).filter((h) => h.via === `conversation:${conversation}`).map((h) => h.id)); | |
| 62 | return waitingConfirms({ app }, user, now).filter((w) => here.has(w.id)); | |
| 63 | } |
src/games/chat.ts +14 −25
| @@ -25,10 +25,8 @@ | ||
| 25 | 25 | */ |
| 26 | 26 | |
| 27 | 27 | import type { App } from "../app.ts"; |
| 28 | import { waitingConfirms } from "../actions/conversation_confirms.ts"; | |
| 29 | import { talk } from "../actions/talk.ts"; | |
| 30 | import { limitToGame } from "../core/conversation_door.ts"; | |
| 31 | import { createConversation, listTurns } from "../core/conversations.ts"; | |
| 28 | import { askThrough, heldIn } from "../actions/talk_door.ts"; | |
| 29 | import { listTurns } from "../core/conversations.ts"; | |
| 32 | 30 | import { proveMinecraft, unproveMinecraft } from "../core/identities.ts"; |
| 33 | 31 | import { readReceipt } from "../crew/receipt.ts"; |
| 34 | 32 | import { publicOrigin } from "../core/public_origin.ts"; |
| @@ -746,34 +744,25 @@ function ask(app: App, box: GameBox, job: Job, user: User): void { | ||
| 746 | 744 | const kept = door |
| 747 | 745 | ? db.query<{ conversation: string }, [string, string]>("SELECT conversation FROM game_talk WHERE box_id = ?1 AND user_id = ?2").get(box.id, user.id)?.conversation |
| 748 | 746 | : undefined; |
| 749 | const into = (id: string) => talk(app, user, job.words, [], "inject", id); | |
| 750 | let id = kept; | |
| 751 | let sent = kept === undefined ? undefined : into(kept); | |
| 752 | const gone = sent !== undefined && !sent.ok && sent.error === "not_found"; | |
| 753 | if (gone) sent = undefined; | |
| 754 | if (sent === undefined) { | |
| 755 | const conversation = createConversation(db, user.id); | |
| 756 | if (!conversation.ok) | |
| 757 | return finish(app, box, job, "too many conversations", ["You hold the most conversations the forge keeps: archive one on /talk first."], "red"); | |
| 758 | id = conversation.value.id; | |
| 759 | // Words typed in game may read and ask about servers, never reach a reversible write | |
| 760 | // (#18218). | |
| 761 | limitToGame(db, id); | |
| 762 | sent = into(id); | |
| 763 | } | |
| 747 | // Words typed in game may read and ask about servers, never reach a reversible write (#18218): | |
| 748 | // Talk's door module limits the conversation, and a kept one that is gone is made anew. | |
| 749 | const sent = askThrough(app, user, job.words, kept); | |
| 750 | if (!sent.ok && sent.error === "too_many") | |
| 751 | return finish(app, box, job, "too many conversations", ["You hold the most conversations the forge keeps: archive one on /talk first."], "red"); | |
| 764 | 752 | if (!sent.ok) return finish(app, box, job, sent.error, [`The crew could not take it: ${sent.error}.`], "red"); |
| 753 | const { conversation: id, gone, said } = sent.value; | |
| 765 | 754 | if (door) |
| 766 | db.query("INSERT OR REPLACE INTO game_talk (box_id, user_id, conversation, created_at) VALUES (?1, ?2, ?3, ?4)").run(box.id, user.id, id!, new Date().toISOString()); | |
| 767 | const waiting: Job = { ...job, kind: "reply", conversation: id! }; | |
| 755 | db.query("INSERT OR REPLACE INTO game_talk (box_id, user_id, conversation, created_at) VALUES (?1, ?2, ?3, ?4)").run(box.id, user.id, id, new Date().toISOString()); | |
| 756 | const waiting: Job = { ...job, kind: "reply", conversation: id }; | |
| 768 | 757 | db.query("UPDATE game_chat_job SET kind = 'reply', conversation = ?2 WHERE id = ?1").run(job.id, waiting.conversation); |
| 769 | db.query("UPDATE game_chat SET outcome = ?2 WHERE id = ?1").run(job.audit_id, sent.value.how); | |
| 758 | db.query("UPDATE game_chat SET outcome = ?2 WHERE id = ?1").run(job.audit_id, said.how); | |
| 770 | 759 | say(app.db, box, { service: job.service, player: job.player, ask: job.ask_id }, [`${gone ? "Your earlier conversation is gone, so this is a new one. " : ""}Asked the crew: the answer comes here and at ${job.origin}/talk/${waiting.conversation}`], user.id); |
| 771 | 760 | const { live } = workersOf(app); |
| 772 | if (sent.value.done === undefined) return; | |
| 761 | if (said.done === undefined) return; | |
| 773 | 762 | live.add(job.id); |
| 774 | 763 | // Talk logs a turn that crashed; here either end is the same: the next look at the jobs |
| 775 | 764 | // answers. |
| 776 | void sent.value.done | |
| 765 | void said.done | |
| 777 | 766 | .catch(() => undefined) |
| 778 | 767 | .then(() => { |
| 779 | 768 | live.delete(job.id); |
| @@ -809,7 +798,7 @@ function closing(app: App, job: Job, link: string): string[] { | ||
| 809 | 798 | } |
| 810 | 799 | } |
| 811 | 800 | } |
| 812 | const held = waitingConfirms({ app }, user)[0]; | |
| 801 | const held = heldIn(app, user, job.conversation)[0]; | |
| 813 | 802 | if (held !== undefined) out.push(`Held for your yes: ${held.does} [Answer it](${link})`); |
| 814 | 803 | return out; |
| 815 | 804 | } |
src/games/door_hold.ts +8 −15
| @@ -11,10 +11,7 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | 13 | import type { Database } from "bun:sqlite"; |
| 14 | import { limitToGame } from "../core/conversation_door.ts"; | |
| 15 | import { appendTurn, createConversation, getConversation } from "../core/conversations.ts"; | |
| 16 | import { hold } from "../core/fence.ts"; | |
| 17 | import { confirmSentence } from "../crew/conversation_ask.ts"; | |
| 14 | import { conversationIn, raiseHeld } from "../actions/talk_door.ts"; | |
| 18 | 15 | import type { GameBox } from "./store.ts"; |
| 19 | 16 | |
| 20 | 17 | /** What was held, or why nothing could be. */ |
| @@ -25,12 +22,10 @@ export type Holding = { ok: true; confirm: string; conversation: string; does: s | ||
| 25 | 22 | */ |
| 26 | 23 | function conversationFor(db: Database, box: GameBox, userId: string): string | undefined { |
| 27 | 24 | const kept = db.query<{ conversation: string }, [string, string]>("SELECT conversation FROM game_talk WHERE box_id = ?1 AND user_id = ?2").get(box.id, userId)?.conversation; |
| 28 | if (kept !== undefined && getConversation(db, userId, kept) !== undefined) return kept; | |
| 29 | const made = createConversation(db, userId); | |
| 30 | if (!made.ok) return undefined; | |
| 31 | limitToGame(db, made.value.id); | |
| 32 | db.query("INSERT OR REPLACE INTO game_talk (box_id, user_id, conversation, created_at) VALUES (?1, ?2, ?3, ?4)").run(box.id, userId, made.value.id, new Date().toISOString()); | |
| 33 | return made.value.id; | |
| 25 | const found = conversationIn(db, userId, kept); | |
| 26 | if (!found.ok) return undefined; | |
| 27 | if (found.value.id !== kept) db.query("INSERT OR REPLACE INTO game_talk (box_id, user_id, conversation, created_at) VALUES (?1, ?2, ?3, ?4)").run(box.id, userId, found.value.id, new Date().toISOString()); | |
| 28 | return found.value.id; | |
| 34 | 29 | } |
| 35 | 30 | |
| 36 | 31 | /** |
| @@ -40,9 +35,7 @@ export function holdBuild(db: Database, box: GameBox, userId: string, words: str | ||
| 40 | 35 | const conversation = conversationFor(db, box, userId); |
| 41 | 36 | if (conversation === undefined) return { ok: false, error: "too many conversations" }; |
| 42 | 37 | const args = { action: "create_server", box: box.name, words, dryRun: false, sha }; |
| 43 | const confirm = hold(db, `conversation:${conversation}`, userId, "games", args, now); | |
| 44 | if (confirm === null) return { ok: false, error: "too many confirms waiting" }; | |
| 45 | const does = confirmSentence("games", args); | |
| 46 | appendTurn(db, userId, conversation, { role: "confirm", text: JSON.stringify({ confirm, tool: "games", does }) }); | |
| 47 | return { ok: true, confirm, conversation, does }; | |
| 38 | const raised = raiseHeld(db, userId, conversation, "games", args, now); | |
| 39 | if (!raised.ok) return { ok: false, error: "too many confirms waiting" }; | |
| 40 | return { ok: true, confirm: raised.value.confirm, conversation, does: raised.value.does }; | |
| 48 | 41 | } |
test/game-write-window.test.ts +9 −66
| @@ -4,75 +4,31 @@ | ||
| 4 | 4 | * the page's Lock now stop writes at once; a window ends by itself; and only a passkey opens one. |
| 5 | 5 | */ |
| 6 | 6 | import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 7 | import { rm } from "node:fs/promises"; | |
| 10 | 8 | import { sayYes } from "../src/actions/conversation_confirms.ts"; |
| 11 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | 9 | import type { Ctx } from "../src/http/context.ts"; |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import type { App } from "../src/app.ts"; | |
| 14 | 11 | import { waitingFor } from "../src/core/fence.ts"; |
| 15 | 12 | import { createSession } from "../src/core/sessions.ts"; |
| 16 | 13 | import { createUser, type User } from "../src/core/users.ts"; |
| 17 | import { gameAsk, runChat } from "../src/games/chat.ts"; | |
| 18 | import { readCompose } from "../src/games/compose.ts"; | |
| 14 | import { runChat } from "../src/games/chat.ts"; | |
| 19 | 15 | import { toldTo } from "../src/games/door.ts"; |
| 20 | import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts"; | |
| 16 | import { grant, type GameBox } from "../src/games/store.ts"; | |
| 21 | 17 | import { doorOf, lockDoor, openWindow, setWindowMinutes, windowMinutes } from "../src/games/write_window.ts"; |
| 22 | 18 | import { forgeHttp } from "../src/http/server.ts"; |
| 19 | import { openRig, request, through, type Rig } from "./helpers/game-door-rig.ts"; | |
| 23 | 20 | import { chatAged } from "./helpers/game-chat-clock.ts"; |
| 24 | 21 | import { quietLogs } from "./helpers/globals.ts"; |
| 25 | 22 | |
| 26 | 23 | quietLogs(); |
| 27 | 24 | |
| 28 | const COMPOSE = `configs: | |
| 29 | velocity_toml: | |
| 30 | content: | | |
| 31 | [servers] | |
| 32 | hub = "hub:25565" | |
| 33 | try = ["hub"] | |
| 34 | ||
| 35 | [forced-hosts] | |
| 36 | "play.example.test" = ["hub"] | |
| 37 | ||
| 38 | services: | |
| 39 | velocity: | |
| 40 | image: itzg/mc-proxy:latest | |
| 41 | ports: ["25565:25565"] | |
| 42 | configs: | |
| 43 | - source: velocity_toml | |
| 44 | target: /config/velocity.toml | |
| 45 | environment: | |
| 46 | TYPE: VELOCITY | |
| 47 | MEMORY: 768M | |
| 48 | hub: | |
| 49 | image: itzg/minecraft-server:latest | |
| 50 | environment: | |
| 51 | TYPE: PAPER | |
| 52 | VERSION: "1.21.6" | |
| 53 | MEMORY: 1G | |
| 54 | `; | |
| 55 | const ADA = "00000000-0000-4000-8000-00000000000a"; | |
| 56 | ||
| 57 | 25 | let dir = ""; |
| 58 | 26 | let app: App; |
| 59 | 27 | let ada: User; |
| 60 | 28 | let box: GameBox; |
| 29 | let rig: Rig; | |
| 30 | const { compose, send, planned } = through(() => rig); | |
| 61 | 31 | |
| 62 | const request = (words: string, more: Record<string, unknown> = {}) => ({ id: crypto.randomUUID() as string, at: Date.now(), uuid: ADA, name: "ada", server: "hub", words, ...more }); | |
| 63 | const compose = async (): Promise<string> => (await readCompose(app, box))!.text; | |
| 64 | const send = async (asks: unknown, run = true) => { | |
| 65 | gameAsk(app, box, asks, await compose(), "http://forge.test", Date.now()); | |
| 66 | if (run) await runChat(app, box.id); | |
| 67 | return toldTo(app.db, box, Date.now()); | |
| 68 | }; | |
| 69 | /** A plan through the proxy, and the request that confirms building it. */ | |
| 70 | const planned = async (name: string) => { | |
| 71 | const plan = request(`give me a flat world called ${name}`); | |
| 72 | const [shown] = await send([plan]); | |
| 73 | expect(shown).toMatchObject({ id: plan.id, confirm: true }); | |
| 74 | return request("yes", { confirms: plan.id }); | |
| 75 | }; | |
| 76 | 32 | const lastRow = () => |
| 77 | 33 | app.db |
| 78 | 34 | .query<{ kind: string; player: string; door: string; outcome: string; write_window: string }, [string]>( |
| @@ -81,21 +37,8 @@ const lastRow = () => | ||
| 81 | 37 | .get(box.id)!; |
| 82 | 38 | |
| 83 | 39 | beforeAll(async () => { |
| 84 | dir = await mkdtemp(join(tmpdir(), "forge-game-window-")); | |
| 85 | app = createApp({ dataDir: dir, port: 0, host: "forge.test", modrinthFetch: (async () => Response.json([])) as unknown as typeof fetch }); | |
| 86 | const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true }); | |
| 87 | if (!u.ok) throw new Error(u.error); | |
| 88 | ada = u.value; | |
| 89 | const repo = await createRepo(app, ada, { name: "net", visibility: "private" }); | |
| 90 | if (!repo.ok) throw new Error(JSON.stringify(repo)); | |
| 91 | const put = await commitToBranch(app, ada, repo.value, { message: "net", files: [{ path: "docker-compose.yml", content: COMPOSE }] }); | |
| 92 | if (!put.ok) throw new Error(JSON.stringify(put.error)); | |
| 93 | createGameBox(app.db, { name: "mc", repo: "ada/net" }); | |
| 94 | box = boxNamed(app.db, "mc")!; | |
| 95 | app.db | |
| 96 | .query("INSERT OR REPLACE INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at, asleep, online_json) VALUES (?1, 'hub', 'running', '', '', 0, 0, '', 0, ?2)") | |
| 97 | .run(box.id, JSON.stringify([{ name: "ada", uuid: ADA }])); | |
| 98 | app.db.query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)").run(box.id, ada.id, ADA, new Date().toISOString()); | |
| 40 | rig = await openRig("forge-game-door-"); | |
| 41 | ({ dir, app, ada, box } = rig); | |
| 99 | 42 | }, 30_000); |
| 100 | 43 | beforeEach(() => { |
| 101 | 44 | app.db.query("DELETE FROM game_chat_job").run(); |
test/helpers/game-door-rig.ts added +93
| @@ -0,0 +1,93 @@ | ||
| 1 | /** | |
| 2 | * A game box on a throwaway forge, for the tests of what the game door does: the proxy's compose | |
| 3 | * file, a linked player, and the `send` and `planned` that put a player's words through the door. | |
| 4 | */ | |
| 5 | import { expect } from "bun:test"; | |
| 6 | import { mkdtemp } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { commitToBranch, createRepo } from "../../src/actions/repos.ts"; | |
| 10 | import { createApp, type App } from "../../src/app.ts"; | |
| 11 | import { createUser, type User } from "../../src/core/users.ts"; | |
| 12 | import { gameAsk, runChat } from "../../src/games/chat.ts"; | |
| 13 | import { readCompose } from "../../src/games/compose.ts"; | |
| 14 | import { toldTo } from "../../src/games/door.ts"; | |
| 15 | import { boxNamed, createGameBox, type GameBox } from "../../src/games/store.ts"; | |
| 16 | ||
| 17 | export const COMPOSE = `configs: | |
| 18 | velocity_toml: | |
| 19 | content: | | |
| 20 | [servers] | |
| 21 | hub = "hub:25565" | |
| 22 | try = ["hub"] | |
| 23 | ||
| 24 | [forced-hosts] | |
| 25 | "play.example.test" = ["hub"] | |
| 26 | ||
| 27 | services: | |
| 28 | velocity: | |
| 29 | image: itzg/mc-proxy:latest | |
| 30 | ports: ["25565:25565"] | |
| 31 | configs: | |
| 32 | - source: velocity_toml | |
| 33 | target: /config/velocity.toml | |
| 34 | environment: | |
| 35 | TYPE: VELOCITY | |
| 36 | MEMORY: 768M | |
| 37 | hub: | |
| 38 | image: itzg/minecraft-server:latest | |
| 39 | environment: | |
| 40 | TYPE: PAPER | |
| 41 | VERSION: "1.21.6" | |
| 42 | MEMORY: 1G | |
| 43 | `; | |
| 44 | export const ADA = "00000000-0000-4000-8000-00000000000a"; | |
| 45 | ||
| 46 | export interface Rig { | |
| 47 | readonly dir: string; | |
| 48 | readonly app: App; | |
| 49 | readonly ada: User; | |
| 50 | readonly box: GameBox; | |
| 51 | } | |
| 52 | ||
| 53 | /** The forge, the admin `ada` linked in game as ADA, and the box `mc` running a proxy and a hub. */ | |
| 54 | export async function openRig(prefix: string): Promise<Rig> { | |
| 55 | const dir = await mkdtemp(join(tmpdir(), prefix)); | |
| 56 | const app = createApp({ dataDir: dir, port: 0, host: "forge.test", modrinthFetch: (async () => Response.json([])) as unknown as typeof fetch }); | |
| 57 | const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true }); | |
| 58 | if (!u.ok) throw new Error(u.error); | |
| 59 | const ada = u.value; | |
| 60 | const repo = await createRepo(app, ada, { name: "net", visibility: "private" }); | |
| 61 | if (!repo.ok) throw new Error(JSON.stringify(repo)); | |
| 62 | const put = await commitToBranch(app, ada, repo.value, { message: "net", files: [{ path: "docker-compose.yml", content: COMPOSE }] }); | |
| 63 | if (!put.ok) throw new Error(JSON.stringify(put.error)); | |
| 64 | createGameBox(app.db, { name: "mc", repo: "ada/net" }); | |
| 65 | const box = boxNamed(app.db, "mc")!; | |
| 66 | app.db | |
| 67 | .query("INSERT OR REPLACE INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at, asleep, online_json) VALUES (?1, 'hub', 'running', '', '', 0, 0, '', 0, ?2)") | |
| 68 | .run(box.id, JSON.stringify([{ name: "ada", uuid: ADA }])); | |
| 69 | app.db.query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)").run(box.id, ada.id, ADA, new Date().toISOString()); | |
| 70 | return { dir, app, ada, box }; | |
| 71 | } | |
| 72 | ||
| 73 | /** One request as the game mod sends it. */ | |
| 74 | export const request = (words: string, more: Record<string, unknown> = {}) => ({ id: crypto.randomUUID() as string, at: Date.now(), uuid: ADA, name: "ada", server: "hub", words, ...more }); | |
| 75 | ||
| 76 | /** The box's compose text, and the asks that go through the door on it. */ | |
| 77 | export function through(rig: () => Rig) { | |
| 78 | const compose = async (): Promise<string> => (await readCompose(rig().app, rig().box))!.text; | |
| 79 | const send = async (asks: unknown, run = true) => { | |
| 80 | const { app, box } = rig(); | |
| 81 | gameAsk(app, box, asks, await compose(), "http://forge.test", Date.now()); | |
| 82 | if (run) await runChat(app, box.id); | |
| 83 | return toldTo(app.db, box, Date.now()); | |
| 84 | }; | |
| 85 | /** A plan through the proxy, and the request that confirms building it. */ | |
| 86 | const planned = async (name: string) => { | |
| 87 | const plan = request(`give me a flat world called ${name}`); | |
| 88 | const [shown] = await send([plan]); | |
| 89 | expect(shown).toMatchObject({ id: plan.id, confirm: true }); | |
| 90 | return request("yes", { confirms: plan.id }); | |
| 91 | }; | |
| 92 | return { compose, send, planned }; | |
| 93 | } |
test/talk-door.test.ts added +139
| @@ -0,0 +1,139 @@ | ||
| 1 | /** | |
| 2 | * One Talk engine for game chat (#18310): a write held in game lives in the player's game | |
| 3 | * conversation, is read back from there by `heldIn`, and is answered on the web page and over the | |
| 4 | * API (the iOS app's door) with the same yes that builds the server once. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; | |
| 7 | import { rm } from "node:fs/promises"; | |
| 8 | import { conversationIn, heldIn, raiseHeld } from "../src/actions/talk_door.ts"; | |
| 9 | import type { App } from "../src/app.ts"; | |
| 10 | import { appendTurn, listTurns } from "../src/core/conversations.ts"; | |
| 11 | import { createSession } from "../src/core/sessions.ts"; | |
| 12 | import { createToken } from "../src/core/tokens.ts"; | |
| 13 | import type { User } from "../src/core/users.ts"; | |
| 14 | import type { GameBox } from "../src/games/store.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { openRig, request, through, type Rig } from "./helpers/game-door-rig.ts"; | |
| 17 | import { chatAged } from "./helpers/game-chat-clock.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | let dir = ""; | |
| 23 | let app: App; | |
| 24 | let ada: User; | |
| 25 | let box: GameBox; | |
| 26 | let servers: Servers; | |
| 27 | let rig: Rig; | |
| 28 | const { compose, send, planned } = through(() => rig); | |
| 29 | ||
| 30 | beforeAll(async () => { | |
| 31 | rig = await openRig("forge-game-door-"); | |
| 32 | ({ dir, app, ada, box } = rig); | |
| 33 | servers = await serve(app); | |
| 34 | }, 30_000); | |
| 35 | beforeEach(() => { | |
| 36 | app.db.query("DELETE FROM game_chat_job").run(); | |
| 37 | app.db.query("DELETE FROM game_door").run(); | |
| 38 | app.db.query("DELETE FROM game_talk").run(); | |
| 39 | app.db.query("DELETE FROM conversation").run(); | |
| 40 | app.db.query("DELETE FROM conversation_held").run(); | |
| 41 | chatAged(app.db, 3_600_001); | |
| 42 | }); | |
| 43 | afterAll(async () => { | |
| 44 | servers.stop(); | |
| 45 | app.close(); | |
| 46 | await rm(dir, { recursive: true, force: true }); | |
| 47 | }); | |
| 48 | ||
| 49 | /** A build held in game, and the game conversation that holds it. */ | |
| 50 | const raised = async (name: string) => { | |
| 51 | const [told] = await send([await planned(name)]); | |
| 52 | expect(told!.text).toStartWith("Held: "); | |
| 53 | const kept = app.db.query<{ conversation: string }, [string]>("SELECT conversation FROM game_talk WHERE box_id = ?1").get(box.id)!.conversation; | |
| 54 | const waiting = heldIn(app, ada, kept); | |
| 55 | expect(waiting).toHaveLength(1); | |
| 56 | return { kept, id: waiting[0]!.id, name }; | |
| 57 | }; | |
| 58 | const post = (path: string, headers: Record<string, string>, body: string) => fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { origin: new URL(servers.url).origin, ...headers }, body }); | |
| 59 | ||
| 60 | test("a held action raised in game is read back from its own game conversation, and no other", async () => { | |
| 61 | const { kept, id } = await raised("here"); | |
| 62 | const other = conversationIn(app.db, ada.id); | |
| 63 | if (!other.ok) throw new Error("no conversation"); | |
| 64 | expect(heldIn(app, ada, other.value.id)).toEqual([]); | |
| 65 | expect(heldIn(app, ada, kept).map((w) => w.id)).toEqual([id]); | |
| 66 | const turns = listTurns(app.db, ada.id, kept); | |
| 67 | expect(turns.ok && turns.value.some((t) => t.role === "confirm" && t.text.includes(id))).toBe(true); | |
| 68 | // A kept conversation that is gone is made anew, limited to the door, and says so. | |
| 69 | const gone = conversationIn(app.db, ada.id, "no-such-conversation"); | |
| 70 | expect(gone.ok && gone.value.gone).toBe(true); | |
| 71 | }, 30_000); | |
| 72 | ||
| 73 | test("on the web: the game conversation shows the held build with its buttons, and Do it builds it once", async () => { | |
| 74 | const { kept, id } = await raised("web"); | |
| 75 | const cookie = `forge_session=${createSession(app.db, ada.id).token}`; | |
| 76 | const page = await (await fetch(`${servers.url}/talk/${kept}`, { headers: { cookie } })).text(); | |
| 77 | expect(page).toContain(`data-confirm-id="${id}"`); | |
| 78 | const yes = await post(`/talk/confirm/${id}`, { cookie, "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, "answer=yes"); | |
| 79 | expect(yes.status).toBe(200); | |
| 80 | expect(await compose()).toContain("\n web:\n"); | |
| 81 | expect(heldIn(app, ada, kept)).toEqual([]); | |
| 82 | expect((await post(`/talk/confirm/${id}`, { cookie, "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, "answer=yes")).status).toBeGreaterThanOrEqual(400); | |
| 83 | }, 30_000); | |
| 84 | ||
| 85 | test("on iOS (the API): the same held build is answered with the person's own rw token, and a no builds nothing", async () => { | |
| 86 | const token = createToken(app.db, ada.id, "ios", "rw").token; | |
| 87 | const auth = { authorization: `Bearer ${token}`, "content-type": "application/json" }; | |
| 88 | const { kept, id } = await raised("ios"); | |
| 89 | const yes = await post(`/api/v1/conversation-confirms/${id}`, auth, JSON.stringify({ answer: "yes" })); | |
| 90 | expect(yes.status).toBe(200); | |
| 91 | expect(await compose()).toContain("\n ios:\n"); | |
| 92 | expect(heldIn(app, ada, kept)).toEqual([]); | |
| 93 | chatAged(app.db, 3_600_001); | |
| 94 | const no = await raised("declined"); | |
| 95 | expect((await post(`/api/v1/conversation-confirms/${no.id}`, auth, JSON.stringify({ answer: "no" }))).status).toBe(200); | |
| 96 | expect(await compose()).not.toContain("\n declined:\n"); | |
| 97 | expect(heldIn(app, ada, no.kept)).toEqual([]); | |
| 98 | }, 30_000); | |
| 99 | ||
| 100 | const kept = () => app.db.query<{ conversation: string }, [string]>("SELECT conversation FROM game_talk WHERE box_id = ?1").all(box.id).map((r) => r.conversation); | |
| 101 | ||
| 102 | test("a reply shows only the confirm held in its own conversation, not one held in another", async () => { | |
| 103 | await send([request("why is the hub slow?")]); | |
| 104 | const [mine] = kept(); | |
| 105 | const other = conversationIn(app.db, ada.id); | |
| 106 | if (!other.ok) throw new Error("no conversation"); | |
| 107 | const there = raiseHeld(app.db, ada.id, other.value.id, "archive", { repo: "ada/net", archived: false, dryRun: false }); | |
| 108 | const here = raiseHeld(app.db, ada.id, mine!, "archive", { repo: "ada/net", archived: true, dryRun: false }); | |
| 109 | if (!there.ok || !here.ok) throw new Error("not held"); | |
| 110 | expect(there.value.does).not.toBe(here.value.does); | |
| 111 | appendTurn(app.db, ada.id, mine!, { role: "agent", text: "It is the plugins." }); | |
| 112 | const said = (await send([])).map((t) => t.text).join("\n"); | |
| 113 | expect(said).toContain(`Held for your yes: ${here.value.does} `); | |
| 114 | expect(said).not.toContain(there.value.does); | |
| 115 | }, 30_000); | |
| 116 | ||
| 117 | test("a reply with nothing held in its own conversation shows no held line, whatever is held elsewhere", async () => { | |
| 118 | await send([request("why is the hub slow?")]); | |
| 119 | const [mine] = kept(); | |
| 120 | const other = conversationIn(app.db, ada.id); | |
| 121 | if (!other.ok) throw new Error("no conversation"); | |
| 122 | raiseHeld(app.db, ada.id, other.value.id, "archive", { repo: "ada/net", archived: true, dryRun: false }); | |
| 123 | appendTurn(app.db, ada.id, mine!, { role: "agent", text: "It is the plugins." }); | |
| 124 | const said = (await send([])).map((t) => t.text).join("\n"); | |
| 125 | expect(said).toContain("It is the plugins."); | |
| 126 | expect(said).not.toContain("Held for your yes:"); | |
| 127 | }, 30_000); | |
| 128 | ||
| 129 | test("asking twice in one box keeps one conversation and one game_talk row", async () => { | |
| 130 | await send([request("why is the hub slow?")]); | |
| 131 | const [one] = kept(); | |
| 132 | chatAged(app.db, 3_600_001); | |
| 133 | const second = (await send([request("and the proxy?")])).map((t) => t.text).join("\n"); | |
| 134 | expect(second).not.toContain("Your earlier conversation is gone"); | |
| 135 | expect(kept()).toEqual([one!]); | |
| 136 | expect(app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM conversation WHERE user_id = ?1").get(ada.id)!.n).toBe(1); | |
| 137 | const turns = listTurns(app.db, ada.id, one!); | |
| 138 | expect(turns.ok && turns.value.filter((t) => t.role === "person").map((t) => t.text)).toEqual(["why is the hub slow?", "and the proxy?"]); | |
| 139 | }); |
new above
offline
The
Doorunion and thelimitrecord serve one door. CalllimitToGamedirectly and add the indirection when a second door exists.