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

opened this in answer to

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

  • Merged. mason/18004-talk-api-a-person-s-sent-files-on-each-t was merged into main as 0e5211b.

Review

Sign in to review this change.
9 files changed +140 −9
docs/features/talk.md +1
@@ -61,6 +61,7 @@ The first message of a conversation opened this way also carries the subject to
6161 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.
6262
6363 - **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).
6465 - **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.
6566 - **MCP:** `say` with `action` list | new | rename | archive | restore, and `conversation` to speak in one.
6667 - **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 = {
66 method: "get",
77 path: "/api/v1/conversation/turns",
88 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)",
1010 auth: true,
1111 role: "member",
1212 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.
9595 export { route as getApiV1Conversations } from "./getApiV1Conversations.ts";
9696 export { route as getApiV1ConversationsIdBuild } from "./getApiV1ConversationsIdBuild.ts";
9797 export { route as getApiV1ConversationsIdBuildVersionsNDiff } from "./getApiV1ConversationsIdBuildVersionsNDiff.ts";
98 export { route as getApiV1ConversationsSearch } from "./getApiV1ConversationsSearch.ts";
9899 export { route as getApiV1Credit } from "./getApiV1Credit.ts";
99100 export { route as getApiV1CrewNow } from "./getApiV1CrewNow.ts";
100101 export { route as getApiV1CrewScorecard } from "./getApiV1CrewScorecard.ts";
src/contract/openapi/schemas/conversation.ts +3 −2
@@ -73,7 +73,7 @@ const TURN_CARD: Schema = obj(
7373
7474 /**
7575 * 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.
7777 */
7878 const TURN: Schema = obj(
7979 {
@@ -90,8 +90,9 @@ const TURN: Schema = obj(
9090 costUsd: orNull(num),
9191 plain: str,
9292 cards: list(ref("TurnCard")),
93 files: list(obj({ id: str, name: str, type: str, size: num })),
9394 },
94 ["limited", "stoppedAt", "work", "costUsd", "plain", "cards"],
95 ["limited", "stoppedAt", "work", "costUsd", "plain", "cards", "files"],
9596 );
9697
9798 const TURNS: Schema = obj(
src/core/conversations.ts +4 −3
@@ -469,9 +469,10 @@ export function findQuery(typed: string): string | undefined {
469469 * The person's conversations whose title or standing turns hold every word of
470470 * `typed`, best match first, each with the turn to open it at. Answered from
471471 * 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).
473474 */
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[] {
475476 const query = findQuery(typed);
476477 if (query === undefined) return [];
477478 const rows = db
@@ -492,7 +493,7 @@ export function findConversations(db: Database, userId: string, typed: string):
492493 const conversation = getConversation(db, userId, conversationId);
493494 if (conversation === undefined) continue;
494495 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;
496497 }
497498 return out;
498499 }
src/http/api/conversation_talk.ts +24 −3
@@ -8,7 +8,7 @@
88 */
99
1010 import { startingIn } from "../../crew/conversation_starting.ts";
11 import { limitRefusal } from "../../contract/page_query.ts";
11 import { cursorRefusal, limitRefusal } from "../../contract/page_query.ts";
1212 import { parseLimit } from "../../contract/page_query.ts";
1313 import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
1414 import { blockedFields } from "../../kernel/blocked.ts";
@@ -21,6 +21,7 @@ import {
2121 createConversation,
2222 DEFAULT_PAGE,
2323 getConversation,
24 findConversations,
2425 listConversations,
2526 listTurns,
2627 MAX_PAGE,
@@ -29,7 +30,7 @@ import {
2930 TITLE_MAX,
3031 type Turn,
3132 } 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";
3334 import { choiceFrom, modelList, setChoice, switchModel } from "../../core/model_choice.ts";
3435 import { modelRefusal } from "../../actions/build_input.ts";
3536 import { WORDS_MAX } from "../../core/fence.ts";
@@ -42,6 +43,7 @@ import { cardsOfReply } from "../../core/talk_cards.ts";
4243 import { fileQueued, queuedOf, turnRunning } from "../../crew/conversation.ts";
4344 import { crossOrigin, type Handler } from "../context.ts";
4445 import { holds, weakEtag } from "../etag.ts";
46 import { OFFSET_LIMIT_MAX, offsetPage, offsetQuery } from "../offset_page.ts";
4547 import { readBounded } from "../limits.ts";
4648 import { apiError, boundedBody, forbidden, json, tryAgain, unauthorized, WINDOW } from "../respond.ts";
4749 import type { Router } from "../router.ts";
@@ -237,7 +239,10 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
237239 // parser every door uses (`core/talk_voice.ts`); a reply that places none is its own text.
238240 const kept = cardsPlaced(ctx.app.db, user.id, conversation.id, all);
239241 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));
241246 // The tag is of the exact bytes sent (so `before` and `limit` give their own), made after the
242247 // person's own access was settled above.
243248 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 {
247252 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
248253 });
249254
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
250269 router.add("GET", "/api/v1/conversations", (ctx) => {
251270 const user = ctx.auth.user;
252271 if (user === undefined) return unauthorized();
@@ -303,6 +322,8 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
303322 }
304323
305324 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;
306327 const ID = /^[0-9a-z]{1,40}$/;
307328 const TITLE_WORDS = `title is text of at most ${TITLE_MAX} characters, on one line`;
308329
src/http/lazy_lists.ts +1
@@ -1475,6 +1475,7 @@ export const API_ROUTES = [
14751475 ["GET", "/api/v1/conversation/files/:id"],
14761476 ["DELETE", "/api/v1/conversation/files/:id"],
14771477 ["GET", "/api/v1/conversation/turns"],
1478 ["GET", "/api/v1/conversations/search"],
14781479 ["GET", "/api/v1/conversations"],
14791480 ["GET", "/api/v1/models"],
14801481 ["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 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs