Public: anyone can read this; the crew can change it.
Talk API: a person's sent files on each turn, and search inside turns #18009
Merged 12h 51m ago, live in production
mason/forge:mason/18004-talk-api-a-person-s-sent-files-on-each-t → main 0 commits fork
9 files
changed +140
−9
- docs/features/talk.md
- src/contract/openapi/routes/getApiV1ConversationTurns.ts
- src/contract/openapi/routes/getApiV1ConversationsSearch.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/schemas/conversation.ts
- src/core/conversations.ts
- src/http/api/conversation_talk.ts
- src/http/lazy_lists.ts
- test/talk-search-files-api.test.ts
docs/features/talk.md +1
| @@ -61,6 +61,7 @@ The first message of a conversation opened this way also carries the subject to | ||
| 61 | 61 | A person has any number. `/talk` is their latest, with the list above it (newest activity first), **New**, and **Archived (n)** as the one filter (`/talk?archived=1`). Each opens at `/talk/<id>`, stable across reloads; Rename and Archive/Restore are plain forms (`POST /talk/:id/rename`, `/talk/:id/archive`, `POST /talk/new`), so they work without the script. The name is also the page's tab title (`<name> · Talk`); an empty name restores "Chat of <day>". Another person's id is 404 everywhere. A message with no conversation named goes to the latest one that is not archived. |
| 62 | 62 | |
| 63 | 63 | - **No cap (#17927):** New is never refused for count and no turn is ever dropped from a long conversation; older turns page back through `before`. Stop ends every reply the person has running, in any conversation. |
| 64 | - **Sent files and search (#18004):** a person turn from `GET …/turns` carries `files: [{id, name, type, size}]` (`[]` when none). `GET /api/v1/conversations/search?q=&limit=&cursor=` answers `{items: [{conversation: {id, title}, turnId, snippet}], next_cursor}` from the search `/talk?find=` uses, over your own conversations only (`turnId` is null when only the title matched; `q` 1 to 100 characters; limit 1 to 200, default 50; a bad value is a 422). | |
| 64 | 65 | - **API:** `GET /api/v1/conversations[?archived=1]`, `POST /api/v1/conversations {title?}`, `PATCH /api/v1/conversations/:id {title?, archived?}`; `conversation` on `POST …/messages` and `GET …/turns?conversation=` picks one. |
| 65 | 66 | - **MCP:** `say` with `action` list | new | rename | archive | restore, and `conversation` to speak in one. |
| 66 | 67 | - **Terminal:** Palette → Conversations: `n` new, `r` rename, `x` archive or restore, `a` the archived list, Enter opens one (its last 50 turns; `s` says something in it, `R` reloads); the same calls, so the web list and stream read what it writes. |
src/contract/openapi/routes/getApiV1ConversationTurns.ts +1 −1
| @@ -6,7 +6,7 @@ export const route: Route = { | ||
| 6 | 6 | method: "get", |
| 7 | 7 | path: "/api/v1/conversation/turns", |
| 8 | 8 | summary: "The signed-in person's conversation with the forge's agent", |
| 9 | detail: "The signed-in person's conversation with the forge's agent: the latest turns, oldest first, and whether an answer is being written now; stoppedAt is \"limit\" when the latest turn ended because it reached its turn or token limit (cut off, not finished; send a short message to go on), else null. An agent turn carries `cards`: each result its text places with a `::show cN` line, as { ref: \"cN\", kind, title, source, tool, at } and, for a chart (kind line, bar or area), series: [{ label, unit?, tone?, points: [{ t?, v }] }] (the exact values the page draws from; levels: true when a value is a level, so read the last), and for any other kind (rows, a receipt) status and rows: [{ label, value, link?, depth? }]; a handle that names no kept result is left out", | |
| 9 | detail: "The signed-in person's conversation with the forge's agent: the latest turns, oldest first, and whether an answer is being written now; stoppedAt is \"limit\" when the latest turn ended because it reached its turn or token limit (cut off, not finished; send a short message to go on), else null. An agent turn carries `cards`: each result its text places with a `::show cN` line, as { ref: \"cN\", kind, title, source, tool, at } and, for a chart (kind line, bar or area), series: [{ label, unit?, tone?, points: [{ t?, v }] }] (the exact values the page draws from; levels: true when a value is a level, so read the last), and for any other kind (rows, a receipt) status and rows: [{ label, value, link?, depth? }]; a handle that names no kept result is left out; a person's turn carries files: [{ id, name, type, size }] (what was sent with it, [] when none)", | |
| 10 | 10 | auth: true, |
| 11 | 11 | role: "member", |
| 12 | 12 | query: { limit: limitTo(MAX_PAGE), before: "string", conversation: "string" }, |
src/contract/openapi/routes/getApiV1ConversationsSearch.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | import { type Route, limitTo } from "../shared.ts"; | |
| 2 | import { OFFSET_LIMIT_MAX } from "../../../http/offset_page.ts"; | |
| 3 | ||
| 4 | export const route: Route = { | |
| 5 | method: "get", | |
| 6 | path: "/api/v1/conversations/search", | |
| 7 | summary: "Search inside the signed-in person's conversations", | |
| 8 | detail: | |
| 9 | "The search of /talk?find=, over the caller's own conversations only (title and turns, every word, the last as a prefix); answers { items: [{ conversation: { id, title }, turnId, snippet }], next_cursor }, best match first, one item per conversation; turnId is null when only the title matched; q is 1 to 100 characters; limit 1 to 200 (default 50), cursor from next_cursor; a bad q, limit or cursor is a 422", | |
| 10 | auth: true, | |
| 11 | role: "member", | |
| 12 | query: { q: "string", limit: limitTo(OFFSET_LIMIT_MAX), cursor: "string" }, | |
| 13 | refuses: [401, 422], | |
| 14 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -95,6 +95,7 @@ export { route as getApiV1ConversationTurns } from "./getApiV1ConversationTurns. | ||
| 95 | 95 | export { route as getApiV1Conversations } from "./getApiV1Conversations.ts"; |
| 96 | 96 | export { route as getApiV1ConversationsIdBuild } from "./getApiV1ConversationsIdBuild.ts"; |
| 97 | 97 | export { route as getApiV1ConversationsIdBuildVersionsNDiff } from "./getApiV1ConversationsIdBuildVersionsNDiff.ts"; |
| 98 | export { route as getApiV1ConversationsSearch } from "./getApiV1ConversationsSearch.ts"; | |
| 98 | 99 | export { route as getApiV1Credit } from "./getApiV1Credit.ts"; |
| 99 | 100 | export { route as getApiV1CrewNow } from "./getApiV1CrewNow.ts"; |
| 100 | 101 | export { route as getApiV1CrewScorecard } from "./getApiV1CrewScorecard.ts"; |
src/contract/openapi/schemas/conversation.ts +3 −2
| @@ -73,7 +73,7 @@ const TURN_CARD: Schema = obj( | ||
| 73 | 73 | |
| 74 | 74 | /** |
| 75 | 75 | * A turn: agent turns also carry `cards`, the results their text places, in the order it places |
| 76 | * them. | |
| 76 | * them; person turns carry `files`, what was sent with them. | |
| 77 | 77 | */ |
| 78 | 78 | const TURN: Schema = obj( |
| 79 | 79 | { |
| @@ -90,8 +90,9 @@ const TURN: Schema = obj( | ||
| 90 | 90 | costUsd: orNull(num), |
| 91 | 91 | plain: str, |
| 92 | 92 | cards: list(ref("TurnCard")), |
| 93 | files: list(obj({ id: str, name: str, type: str, size: num })), | |
| 93 | 94 | }, |
| 94 | ["limited", "stoppedAt", "work", "costUsd", "plain", "cards"], | |
| 95 | ["limited", "stoppedAt", "work", "costUsd", "plain", "cards", "files"], | |
| 95 | 96 | ); |
| 96 | 97 | |
| 97 | 98 | const TURNS: Schema = obj( |
src/core/conversations.ts +4 −3
| @@ -469,9 +469,10 @@ export function findQuery(typed: string): string | undefined { | ||
| 469 | 469 | * The person's conversations whose title or standing turns hold every word of |
| 470 | 470 | * `typed`, best match first, each with the turn to open it at. Answered from |
| 471 | 471 | * the `conversation_find` index, never by reading turns; only the person's |
| 472 | * own conversations are ever looked at. | |
| 472 | * own conversations are ever looked at. `max` is how many it answers (the page's own list is | |
| 473 | * `FIND_MAX`; the API pages through up to 200, one row's reach). | |
| 473 | 474 | */ |
| 474 | export function findConversations(db: Database, userId: string, typed: string): Found[] { | |
| 475 | export function findConversations(db: Database, userId: string, typed: string, max: number = FIND_MAX): Found[] { | |
| 475 | 476 | const query = findQuery(typed); |
| 476 | 477 | if (query === undefined) return []; |
| 477 | 478 | const rows = db |
| @@ -492,7 +493,7 @@ export function findConversations(db: Database, userId: string, typed: string): | ||
| 492 | 493 | const conversation = getConversation(db, userId, conversationId); |
| 493 | 494 | if (conversation === undefined) continue; |
| 494 | 495 | out.push({ conversation, turnId: hit.turnId === "" ? undefined : hit.turnId, snippet: hit.snip }); |
| 495 | if (out.length >= FIND_MAX) break; | |
| 496 | if (out.length >= max) break; | |
| 496 | 497 | } |
| 497 | 498 | return out; |
| 498 | 499 | } |
src/http/api/conversation_talk.ts +24 −3
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import { startingIn } from "../../crew/conversation_starting.ts"; |
| 11 | import { limitRefusal } from "../../contract/page_query.ts"; | |
| 11 | import { cursorRefusal, limitRefusal } from "../../contract/page_query.ts"; | |
| 12 | 12 | import { parseLimit } from "../../contract/page_query.ts"; |
| 13 | 13 | import { noTalkAccountBlocked } from "../../actions/blocked_words.ts"; |
| 14 | 14 | import { blockedFields } from "../../kernel/blocked.ts"; |
| @@ -21,6 +21,7 @@ import { | ||
| 21 | 21 | createConversation, |
| 22 | 22 | DEFAULT_PAGE, |
| 23 | 23 | getConversation, |
| 24 | findConversations, | |
| 24 | 25 | listConversations, |
| 25 | 26 | listTurns, |
| 26 | 27 | MAX_PAGE, |
| @@ -29,7 +30,7 @@ import { | ||
| 29 | 30 | TITLE_MAX, |
| 30 | 31 | type Turn, |
| 31 | 32 | } from "../../core/conversations.ts"; |
| 32 | import { FILE_WORDS, fileBytes, fileOwnedBy, FILES_PER_MESSAGE, IMAGE_MAX, pendingAmong, removePending, storeFile } from "../../core/conversation_files.ts"; | |
| 33 | import { FILE_WORDS, fileBytes, filesOfTurns, fileOwnedBy, FILES_PER_MESSAGE, IMAGE_MAX, pendingAmong, removePending, storeFile } from "../../core/conversation_files.ts"; | |
| 33 | 34 | import { choiceFrom, modelList, setChoice, switchModel } from "../../core/model_choice.ts"; |
| 34 | 35 | import { modelRefusal } from "../../actions/build_input.ts"; |
| 35 | 36 | import { WORDS_MAX } from "../../core/fence.ts"; |
| @@ -42,6 +43,7 @@ import { cardsOfReply } from "../../core/talk_cards.ts"; | ||
| 42 | 43 | import { fileQueued, queuedOf, turnRunning } from "../../crew/conversation.ts"; |
| 43 | 44 | import { crossOrigin, type Handler } from "../context.ts"; |
| 44 | 45 | import { holds, weakEtag } from "../etag.ts"; |
| 46 | import { OFFSET_LIMIT_MAX, offsetPage, offsetQuery } from "../offset_page.ts"; | |
| 45 | 47 | import { readBounded } from "../limits.ts"; |
| 46 | 48 | import { apiError, boundedBody, forbidden, json, tryAgain, unauthorized, WINDOW } from "../respond.ts"; |
| 47 | 49 | import type { Router } from "../router.ts"; |
| @@ -237,7 +239,10 @@ export function conversationTalkRoutes(router: Router<Handler>): void { | ||
| 237 | 239 | // parser every door uses (`core/talk_voice.ts`); a reply that places none is its own text. |
| 238 | 240 | const kept = cardsPlaced(ctx.app.db, user.id, conversation.id, all); |
| 239 | 241 | const plainOf = (text: string) => ((p) => (p === text ? {} : { plain: p }))(plainVoice(text, kept)); |
| 240 | const shown = all.map((t) => (t.role === "agent" ? { ...t, ...(t.limited === true ? { stoppedAt: "limit" } : {}), work: works.get(t.id) ?? null, costUsd: costs.get(t.id) ?? null, ...plainOf(t.text), cards: t.failed === true ? [] : cardsOfReply(t.text, kept) } : t)); | |
| 242 | // A person's turn carries the files sent with it: `{id, name, type, size}`, none as []. | |
| 243 | const sent = filesOfTurns(ctx.app.db, user.id, all.filter((t) => t.role === "person").map((t) => t.id)); | |
| 244 | const filesOf = (id: string) => (sent.get(id) ?? []).map(({ id: fid, name, type, size }) => ({ id: fid, name, type, size })); | |
| 245 | const shown = all.map((t) => (t.role === "person" ? { ...t, files: filesOf(t.id) } : t.role === "agent" ? { ...t, ...(t.limited === true ? { stoppedAt: "limit" } : {}), work: works.get(t.id) ?? null, costUsd: costs.get(t.id) ?? null, ...plainOf(t.text), cards: t.failed === true ? [] : cardsOfReply(t.text, kept) } : t)); | |
| 241 | 246 | // The tag is of the exact bytes sent (so `before` and `limit` give their own), made after the |
| 242 | 247 | // person's own access was settled above. |
| 243 | 248 | const text = JSON.stringify({ running: turnRunning(ctx.app, user.id, conversation.id), stoppedAt: stoppedAt(all, ctx.url.searchParams.has("before")), conversation: conversation.id, totalUsd: conversationTotal(ctx.app.db, conversation.id) ?? null, queued: queuedOf(ctx.app, user.id, conversation.id).map((q) => ({ id: q.id, text: q.text })), turns: shown }); |
| @@ -247,6 +252,20 @@ export function conversationTalkRoutes(router: Router<Handler>): void { | ||
| 247 | 252 | return new Response(text, { headers: { "content-type": "application/json", ...headers } }); |
| 248 | 253 | }); |
| 249 | 254 | |
| 255 | // The search of `/talk?find=`, as data: the person's own conversations, best match first, each | |
| 256 | // with the turn to open it at (absent when only the title matched). | |
| 257 | router.add("GET", "/api/v1/conversations/search", (ctx) => { | |
| 258 | const user = ctx.auth.user; | |
| 259 | if (user === undefined) return unauthorized(); | |
| 260 | const page = offsetQuery(ctx.url.searchParams); | |
| 261 | if ("error" in page) return page.error === "invalid_limit" ? limitRefusal(OFFSET_LIMIT_MAX) : cursorRefusal("cursor is the next_cursor of the page before"); | |
| 262 | const q = ctx.url.searchParams.get("q") ?? ""; | |
| 263 | if (q.trim() === "" || q.length > FIND_CHARS) return apiError("invalid_query", 422, `q is text of 1 to ${FIND_CHARS} characters`); | |
| 264 | const found = findConversations(ctx.app.db, user.id, q, OFFSET_LIMIT_MAX); | |
| 265 | const rows = found.map((f) => ({ conversation: { id: f.conversation.id, title: f.conversation.title }, turnId: f.turnId ?? null, snippet: f.snippet })); | |
| 266 | return new Response(JSON.stringify(offsetPage(rows, page.limit, page.offset)), { headers: { "content-type": "application/json", "cache-control": "private, no-store", vary: "authorization, cookie" } }); | |
| 267 | }); | |
| 268 | ||
| 250 | 269 | router.add("GET", "/api/v1/conversations", (ctx) => { |
| 251 | 270 | const user = ctx.auth.user; |
| 252 | 271 | if (user === undefined) return unauthorized(); |
| @@ -303,6 +322,8 @@ export function conversationTalkRoutes(router: Router<Handler>): void { | ||
| 303 | 322 | } |
| 304 | 323 | |
| 305 | 324 | const MODEL_WORDS = "that model is not offered to you now; GET /api/v1/models lists the ones that are"; |
| 325 | /** The longest search text taken, as the page's own box. */ | |
| 326 | const FIND_CHARS = 100; | |
| 306 | 327 | const ID = /^[0-9a-z]{1,40}$/; |
| 307 | 328 | const TITLE_WORDS = `title is text of at most ${TITLE_MAX} characters, on one line`; |
| 308 | 329 |
src/http/lazy_lists.ts +1
| @@ -1475,6 +1475,7 @@ export const API_ROUTES = [ | ||
| 1475 | 1475 | ["GET", "/api/v1/conversation/files/:id"], |
| 1476 | 1476 | ["DELETE", "/api/v1/conversation/files/:id"], |
| 1477 | 1477 | ["GET", "/api/v1/conversation/turns"], |
| 1478 | ["GET", "/api/v1/conversations/search"], | |
| 1478 | 1479 | ["GET", "/api/v1/conversations"], |
| 1479 | 1480 | ["GET", "/api/v1/models"], |
| 1480 | 1481 | ["POST", "/api/v1/conversations"], |
test/talk-search-files-api.test.ts added +91
| @@ -0,0 +1,91 @@ | ||
| 1 | /** Sent files on each person turn and search inside turns, over the API (#18004). */ | |
| 2 | ||
| 3 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | import { tmpdir } from "node:os"; | |
| 6 | import { join } from "node:path"; | |
| 7 | import { createApp, type App } from "../src/app.ts"; | |
| 8 | import { appendTurn, newConversation, openConversation, renameConversation } from "../src/core/conversations.ts"; | |
| 9 | import { attach, storeFile } from "../src/core/conversation_files.ts"; | |
| 10 | import { createToken } from "../src/core/tokens.ts"; | |
| 11 | import { createUser } from "../src/core/users.ts"; | |
| 12 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 13 | import { quietLogs } from "./helpers/globals.ts"; | |
| 14 | ||
| 15 | quietLogs(); | |
| 16 | ||
| 17 | describe("talk API: files and search (#18004)", () => { | |
| 18 | let dir: string; | |
| 19 | let app: App; | |
| 20 | let servers: Servers; | |
| 21 | let ana: { id: string; token: string }; | |
| 22 | let bo: { id: string; token: string }; | |
| 23 | const get = (path: string, t: string) => fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${t}` } }); | |
| 24 | ||
| 25 | beforeAll(async () => { | |
| 26 | dir = await mkdtemp(join(tmpdir(), "forge-talk-search-")); | |
| 27 | app = createApp({ dataDir: dir, port: 0, host: "forge.test" }); | |
| 28 | servers = await serve(app); | |
| 29 | const mk = async (username: string) => { | |
| 30 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase" }); | |
| 31 | if (!made.ok) throw new Error(made.error); | |
| 32 | return { id: made.value.id, token: createToken(app.db, made.value.id, "personal", "ro").token }; | |
| 33 | }; | |
| 34 | ana = await mk("ana"); | |
| 35 | bo = await mk("bo"); | |
| 36 | }); | |
| 37 | afterAll(async () => { | |
| 38 | servers.stop(); | |
| 39 | await rm(dir, { recursive: true, force: true }); | |
| 40 | }); | |
| 41 | ||
| 42 | test("a person turn carries the files sent with it, an agent turn none", async () => { | |
| 43 | const c = openConversation(app.db, ana.id); | |
| 44 | const stored = storeFile(app.db, dir, ana.id, "notes.txt", new TextEncoder().encode("hello")); | |
| 45 | if (!stored.ok) throw new Error(stored.error); | |
| 46 | const said = appendTurn(app.db, ana.id, c.id, { role: "person", text: "see the file" }); | |
| 47 | const plain = appendTurn(app.db, ana.id, c.id, { role: "person", text: "no file" }); | |
| 48 | if (!said.ok || !plain.ok) throw new Error("turn"); | |
| 49 | attach(app.db, [stored.value], said.value.id); | |
| 50 | const body = (await (await get("/api/v1/conversation/turns", ana.token)).json()) as { turns: { id: string; files?: unknown }[] }; | |
| 51 | expect(body.turns.find((t) => t.id === said.value.id)!.files).toEqual([{ id: stored.value.id, name: "notes.txt", type: "text/plain", size: 5 }]); | |
| 52 | expect(body.turns.find((t) => t.id === plain.value.id)!.files).toEqual([]); | |
| 53 | }); | |
| 54 | ||
| 55 | test("search answers the caller's own turns, with a cursor and limit", async () => { | |
| 56 | const c = newConversation(app.db, ana.id); | |
| 57 | renameConversation(app.db, ana.id, c.id, "Zebra plans"); | |
| 58 | const t = appendTurn(app.db, ana.id, c.id, { role: "person", text: "the quokka migration timetable" }); | |
| 59 | if (!t.ok) throw new Error("turn"); | |
| 60 | const theirs = newConversation(app.db, bo.id); | |
| 61 | appendTurn(app.db, bo.id, theirs.id, { role: "person", text: "quokka secrets of bo" }); | |
| 62 | const res = await get("/api/v1/conversations/search?q=quokka", ana.token); | |
| 63 | expect(res.status).toBe(200); | |
| 64 | const body = (await res.json()) as { items: { conversation: { id: string; title: string }; turnId: string; snippet: string }[]; next_cursor: string | null }; | |
| 65 | expect(body.items).toHaveLength(1); | |
| 66 | expect(body.items[0]!.conversation).toEqual({ id: c.id, title: "Zebra plans" }); | |
| 67 | expect(body.items[0]!.turnId).toBe(t.value.id); | |
| 68 | expect(body.items[0]!.snippet).toContain("quokka"); | |
| 69 | expect(body.next_cursor).toBeNull(); | |
| 70 | expect(JSON.stringify(body)).not.toContain("secrets of bo"); | |
| 71 | }); | |
| 72 | ||
| 73 | test("a cursor pages the hits", async () => { | |
| 74 | for (const n of [1, 2, 3]) { | |
| 75 | const c = newConversation(app.db, bo.id); | |
| 76 | appendTurn(app.db, bo.id, c.id, { role: "person", text: `walrus number ${n}` }); | |
| 77 | } | |
| 78 | const first = (await (await get("/api/v1/conversations/search?q=walrus&limit=2", bo.token)).json()) as { items: unknown[]; next_cursor: string }; | |
| 79 | expect(first.items).toHaveLength(2); | |
| 80 | const next = (await (await get(`/api/v1/conversations/search?q=walrus&limit=2&cursor=${first.next_cursor}`, bo.token)).json()) as { items: unknown[]; next_cursor: string | null }; | |
| 81 | expect(next.items).toHaveLength(1); | |
| 82 | expect(next.next_cursor).toBeNull(); | |
| 83 | }); | |
| 84 | ||
| 85 | test("a bad q, limit or cursor is a 422; no token is a 401", async () => { | |
| 86 | for (const q of ["?q=", `?q=${"x".repeat(101)}`, "?q=a&limit=0", "?q=a&cursor=zz"]) { | |
| 87 | expect((await get(`/api/v1/conversations/search${q}`, ana.token)).status).toBe(422); | |
| 88 | } | |
| 89 | expect((await fetch(`${servers.url}/api/v1/conversations/search?q=a`)).status).toBe(401); | |
| 90 | }); | |
| 91 | }); |
new above
offline