Public: anyone can read this; the crew can change it.

A person saves a /traces search by name and reopens it from the list and the palette #18381

opened this

Merged 4h 7m ago, live in production

torque/forge:torque/18369-a-person-saves-a-traces-search-by-name-a → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/18369-a-person-saves-a-traces-search-by-name-a was merged into main as db6a2d2.

Review

Sign in to review this change.
17 files changed +581 −10
docs/features/traces.md +10
@@ -64,3 +64,13 @@ A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter
6464 ## One trace as a tree (#18022)
6565
6666 `GET /api/v1/traces/:id` answers the thread, its turns and their steps as one tree, rebuilt from the raw log with `parseRunLog` (a Talk turn's log is a run log): the thread's figures are the list's row (model, account, tokens in, cached and out, cost, outcome, started, ended, steps, errors), each step has its start and end in ms, kind, name, line, model, tokens and outcome (a run log holds no tokens per step, so those are 0). `timed` is false where the log kept no times. `truncated` is true when the log's start was cut (it is read from its last 512 KB) or it holds more than `MAX_STEPS` (20,000) steps. A trace the caller may not see answers exactly as an unknown id: 404 `not_found`. The tree is answered whole (about 15 ms for 5,000 steps). Code: `readTraceTree` in `src/http/api/traces.ts`.
67
68 ## Saved searches (#18369)
69
70 A search you repeat (a repository, a model, a failed outcome, a tool) is kept under a name and is one tap away. A saved search is a name and the query string `/traces` already takes; each person keeps at most 50, private to them, and a name used twice replaces its query. A trace is never touched: removing deletes the saved query only, so the control says so and asks for no typed name.
71
72 - **Page:** with a filter set, `/traces` shows **Name this search** and **Save search**; the saved searches are links above the results, in the command palette on that page (category "Saved trace searches"), and **Remove a saved search** lists a small button for each. `POST /traces/saved` and `POST /traces/saved/<id>/remove` are same-origin forms; a cross-site post is a 403. The 51st is refused with why.
73 - **API:** `GET /api/v1/traces/saved` lists them (`{ items: [{ id, name, query, href, dropped }], limit }`), `POST` with `{ name, query }` keeps one (201; 422 `bad_name`, `empty_search` or `limit_reached`), `DELETE /api/v1/traces/saved/<id>` removes one (404 for another person's).
74 - **MCP:** the `trace` tool's `action: "saved"` lists, with `name` and `query` keeps, with `remove` (an id) ends one.
75 - **Terminal:** in Traces, `b` types the start of a saved name and Enter opens it, `w` names the filters on screen and keeps them, `x` removes the search last opened.
76 - **Opening re-reads the query** through the list's own validator: a facet that no longer exists (an outcome the forge dropped) is left out and the page, the API (`dropped`) and the terminal say which. Names are escaped everywhere. Code: `src/trace/saved.ts`, `src/web/pages/traces_saved.ts`.
src/contract/openapi/routes/deleteApiV1TracesSavedId.ts added +14
@@ -0,0 +1,14 @@
1 import { bool, obj } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 export const route: Route = {
5 method: "delete",
6 path: "/api/v1/traces/saved/{id}",
7 summary: "Remove one of your saved /traces searches",
8 detail:
9 "Removes the saved search only: no trace is touched. Another person's saved search, or an unknown id, is a 404 not_found. Answers { removed: true }",
10 auth: true,
11 role: "member",
12 response: obj({ removed: bool }),
13 refuses: [401, 403, 404],
14 };
src/contract/openapi/routes/getApiV1TracesSaved.ts added +14
@@ -0,0 +1,14 @@
1 import { int, list, obj, str } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 export const route: Route = {
5 method: "get",
6 path: "/api/v1/traces/saved",
7 summary: "Your saved /traces searches",
8 detail:
9 "The caller's own saved searches, by name: { items: [{ id, name, query, href, dropped }], limit }. `query` is the query string `/traces` and `GET /api/v1/traces` take; each is read again through the list's validator, so `href` carries only what still holds and `dropped` names the facets that no longer do. Private to the caller: nobody else's are listed",
10 auth: true,
11 role: "member",
12 response: obj({ items: list(obj({ id: str, name: str, query: str, href: str, dropped: list(str) })), limit: int }),
13 refuses: [401],
14 };
src/contract/openapi/routes/index.ts +3
@@ -44,6 +44,7 @@ export { route as deleteApiV1SecretsScopeName } from "./deleteApiV1SecretsScopeN
4444 export { route as deleteApiV1Sessions } from "./deleteApiV1Sessions.ts";
4545 export { route as deleteApiV1TimersKey } from "./deleteApiV1TimersKey.ts";
4646 export { route as deleteApiV1TokensId } from "./deleteApiV1TokensId.ts";
47 export { route as deleteApiV1TracesSavedId } from "./deleteApiV1TracesSavedId.ts";
4748 export { route as deleteApiV1UserDevicesId } from "./deleteApiV1UserDevicesId.ts";
4849 export { route as deleteApiV1UserKeysId } from "./deleteApiV1UserKeysId.ts";
4950 export { route as deleteApiV1UserOriginAppsId } from "./deleteApiV1UserOriginAppsId.ts";
@@ -282,6 +283,7 @@ export { route as getApiV1Tokens } from "./getApiV1Tokens.ts";
282283 export { route as getApiV1Traces } from "./getApiV1Traces.ts";
283284 export { route as getApiV1TracesCompare } from "./getApiV1TracesCompare.ts";
284285 export { route as getApiV1TracesId } from "./getApiV1TracesId.ts";
286 export { route as getApiV1TracesSaved } from "./getApiV1TracesSaved.ts";
285287 export { route as getApiV1Usage } from "./getApiV1Usage.ts";
286288 export { route as getApiV1User } from "./getApiV1User.ts";
287289 export { route as getApiV1UserAssigned } from "./getApiV1UserAssigned.ts";
@@ -539,6 +541,7 @@ export { route as postApiV1Timers } from "./postApiV1Timers.ts";
539541 export { route as postApiV1TimersFinish } from "./postApiV1TimersFinish.ts";
540542 export { route as postApiV1Tokens } from "./postApiV1Tokens.ts";
541543 export { route as postApiV1TracesImport } from "./postApiV1TracesImport.ts";
544 export { route as postApiV1TracesSaved } from "./postApiV1TracesSaved.ts";
542545 export { route as postApiV1UserDevices } from "./postApiV1UserDevices.ts";
543546 export { route as postApiV1UserEmailVerify } from "./postApiV1UserEmailVerify.ts";
544547 export { route as postApiV1UserKeys } from "./postApiV1UserKeys.ts";
src/contract/openapi/routes/postApiV1TracesSaved.ts added +17
@@ -0,0 +1,17 @@
1 import { list, obj, str } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 export const route: Route = {
5 method: "post",
6 path: "/api/v1/traces/saved",
7 summary: "Save a /traces search under a name",
8 detail:
9 "Keep `query` (the query string `/traces` takes, validated and put in a fixed order, no page cursor) under `name` (1 to 60 characters on one line). The same name again replaces its query. At most 50 a person: the 51st is a 422 limit_reached saying so. A search with no filter is a 422 empty_search. Answers the saved search as the list gives it. A session caller's cross-origin request is refused (403)",
10 auth: true,
11 role: "member",
12 status: 201,
13 body: { name: "string", query: "string" },
14 response: obj({ id: str, name: str, query: str, href: str, dropped: list(str) }),
15 errorStatus: { 422: "bad_name, empty_search or limit_reached; the sentence says which" },
16 refuses: [401, 403],
17 };
src/core/account_purge.ts +2
@@ -53,6 +53,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5353 // An imported session file is private to the person who imported it; the index row goes with
5454 // them.
5555 "trace_index.owner": DELETE,
56 // A saved /traces search is private to the person who named it; it goes with them.
57 "trace_saved.user_id": DELETE,
5658 "access_link.created_by": FORMER,
5759 // The admin who made an integration's lookup key: the key stays, as the former account's.
5860 "connection_lookup_key.created_by": FORMER,
src/core/migration-pins/20261206075300-trace-saved.pin added +1
@@ -0,0 +1,1 @@
1 a8ed6d6b39f2c47ede9c34ecd3a500342f4e15e0f14e8d2c139f78bafbfbf7d7
src/core/migrations/20261206075300-trace-saved.ts added +13
@@ -0,0 +1,13 @@
1 // A person's saved /traces searches (#18369): a name and the query string the list already takes,
2 // private to the person (`user_id`), a name once per person. At most 50 a person is kept by
3 // `trace/saved.ts`. Additive: a new table.
4 export default `
5 CREATE TABLE IF NOT EXISTS trace_saved (
6 id TEXT PRIMARY KEY,
7 user_id TEXT NOT NULL,
8 name TEXT NOT NULL,
9 query TEXT NOT NULL,
10 created_at TEXT NOT NULL,
11 UNIQUE (user_id, name)
12 );
13 `;
src/http/api/traces.ts +42 −1
@@ -13,10 +13,11 @@ import { readTrace, type TraceView } from "../../trace/read.ts";
1313 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1414 import { importSession } from "../../trace/import.ts";
1515 import { LIST_PARAMETERS, listSeenTraces, readListAsk, TRACE_ID, traceTree } from "../../trace/tree.ts";
16 import { cleanName, MAX_SAVED, openedSaved, openSaved, removeSaved, SAVE_WORDS, saveSearch, type OpenedSearch } from "../../trace/saved.ts";
1617 import { MAX_LIMIT } from "../../trace/index_table.ts";
1718 import type { Handler } from "../context.ts";
1819 import { BODY_CAPS, readBounded } from "../limits.ts";
19 import { apiError, json, requireScope } from "../respond.ts";
20 import { apiError, body, json, requireScope } from "../respond.ts";
2021 import type { Router } from "../router.ts";
2122
2223 export const listTraces: Handler = (ctx) => {
@@ -105,8 +106,48 @@ export const compareTraces: Handler = async (ctx) => {
105106 });
106107 };
107108
109 const savedBody = (s: OpenedSearch) => ({ id: s.id, name: s.name, query: s.query, href: s.href, dropped: s.dropped });
110 const priv = { "cache-control": "private, no-store", vary: "authorization, cookie" };
111
112 /**
113 * GET /api/v1/traces/saved (#18369): the caller's own saved searches, each re-read through the
114 * list's validator.
115 */
116 export const listSaved: Handler = (ctx) => {
117 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
118 const denied = requireScope(ctx, "ro");
119 if (denied) return denied;
120 return new Response(JSON.stringify({ items: openedSaved(ctx.app.db, ctx.auth.user!.id).map(savedBody), limit: MAX_SAVED }), { headers: { "content-type": "application/json", ...priv } });
121 };
122
123 /**
124 * POST /api/v1/traces/saved: `{ name, query }` keeps a search; 422 says why a name or the 51st is
125 * refused.
126 */
127 export const saveTrace: Handler = async (ctx) => {
128 const denied = requireScope(ctx, "rw");
129 if (denied) return denied;
130 const input = await body(ctx.request);
131 const query = typeof input["query"] === "string" ? input["query"].replace(/^\?/, "").slice(0, 2000) : "";
132 if (cleanName(input["name"]) === undefined) return apiError("bad_name", 422, SAVE_WORDS.bad_name);
133 const made = saveSearch(ctx.app.db, ctx.auth.user!.id, input["name"], query);
134 if (!made.ok) return apiError(made.error, 422, SAVE_WORDS[made.error]);
135 return json(savedBody(openSaved(made.value)), 201);
136 };
137
138 /** DELETE /api/v1/traces/saved/:id: only the caller's own saved search; no trace is touched. */
139 export const removeSavedTrace: Handler = (ctx) => {
140 const denied = requireScope(ctx, "rw");
141 if (denied) return denied;
142 if (!removeSaved(ctx.app.db, ctx.auth.user!.id, ctx.params.id ?? "")) return apiError("not_found", 404, "no such saved search");
143 return json({ removed: true });
144 };
145
108146 export function traceRoutes(router: Router<Handler>): void {
109147 router.add("POST", "/api/v1/traces/import", importTrace);
148 router.add("GET", "/api/v1/traces/saved", listSaved);
149 router.add("POST", "/api/v1/traces/saved", saveTrace);
150 router.add("DELETE", "/api/v1/traces/saved/:id", removeSavedTrace);
110151 router.add("GET", "/api/v1/traces/compare", compareTraces);
111152 router.add("GET", "/api/v1/traces/:id", readTraceTree);
112153 router.add("GET", "/api/v1/traces", listTraces);
src/http/lazy_lists.ts +5
@@ -727,6 +727,8 @@ export const OPERATIONS_ROUTES = [
727727 ["GET", "/__forge/domains/ask"],
728728 ["GET", "/runs/:id"],
729729 ["GET", "/traces"],
730 ["POST", "/traces/saved"],
731 ["POST", "/traces/saved/:id/remove"],
730732 ["GET", "/traces/:id"],
731733 ["GET", "/traces/:id/steps/:n"],
732734 ["GET", "/traces/:id/compare/:other"],
@@ -1539,6 +1541,9 @@ export const API_ROUTES = [
15391541 ["POST", "/api/v1/conversations"],
15401542 ["PATCH", "/api/v1/conversations/:id"],
15411543 ["POST", "/api/v1/traces/import"],
1544 ["GET", "/api/v1/traces/saved"],
1545 ["POST", "/api/v1/traces/saved"],
1546 ["DELETE", "/api/v1/traces/saved/:id"],
15421547 ["GET", "/api/v1/traces/compare"],
15431548 ["GET", "/api/v1/traces/:id"],
15441549 ["GET", "/api/v1/traces"],
src/http/mcp/tools/trace.ts +16 −3
@@ -2,14 +2,15 @@ import { sharedHref, shareRun, unshareRun } from "../../../actions/trace_share.t
22 import { compareRows, compareViews, readCompared } from "../../../trace/compare.ts";
33 import { readTrace, traceHref, traceRows } from "../../../trace/read.ts";
44 import { LIST_OUTCOMES, listSeenTraces, readListAsk, seenTraceRow, treeOf } from "../../../trace/tree.ts";
5 import { cleanName, openedSaved, openSaved, removeSaved, SAVE_WORDS, saveSearch } from "../../../trace/saved.ts";
56 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
67
78 const ID = /^[0-9A-Za-z_-]{1,64}$/;
8 const ACTIONS = ["read", "list", "compare", "share", "unshare"] as const;
9 const ACTIONS = ["read", "list", "compare", "share", "unshare", "saved"] as const;
910
1011 export const tool: Tool = {
1112 name: "trace",
12 doc: "`{ repo, action?, run?, with? }`: a crew run read as a trace (#17995). `list` (default without `run`): the repository's traces as `GET /api/v1/traces` answers them (`{ items, next_cursor }`), newest first, filtered by `kind`, `model`, `outcome`, `tool`, `file`, `since`, `until`, a page of `limit` at a time (`cursor` is the last `next_cursor`); `read` (default with `run`): the trace as lines, one a step, as the page and terminal show, and `tree`, the API's trace tree; `compare` with `with`: two runs of one issue side by side, steps, failed, time, tokens, cost and outcome with B − A; `share`: the repository owner's share link for the run (secrets redacted, off until made, shown once); `unshare`: end it",
13 doc: "`{ repo, action?, run?, with? }`: a crew run read as a trace (#17995). `list` (default without `run`): the repository's traces as `GET /api/v1/traces` answers them (`{ items, next_cursor }`), newest first, filtered by `kind`, `model`, `outcome`, `tool`, `file`, `since`, `until`, a page of `limit` at a time (`cursor` is the last `next_cursor`); `read` (default with `run`): the trace as lines, one a step, as the page and terminal show, and `tree`, the API's trace tree; `compare` with `with`: two runs of one issue side by side, steps, failed, time, tokens, cost and outcome with B − A; `share`: the repository owner's share link for the run (secrets redacted, off until made, shown once); `unshare`: end it; `saved` (no `repo`): your saved /traces searches, `name` with `query` (the list's query string) keeps one, `remove` (its id) ends one, never a trace",
1314 description: "Read, list or compare crew-run traces; an owner makes or ends a redacted share link.",
1415 inputSchema: {
1516 type: "object",
@@ -26,13 +27,25 @@ export const tool: Tool = {
2627 since: { type: "string", description: "list: from this date or ISO 8601 instant" },
2728 until: { type: "string", description: "list: before this date or ISO 8601 instant" },
2829 limit: { type: "integer", description: "list: rows a page, 1 to 200" },
30 name: { type: "string", description: "saved: keep the search under this name" },
31 query: { type: "string", description: "saved: the /traces query string to keep" },
32 remove: { type: "string", description: "saved: the id of a saved search to remove" },
2933 cursor: { type: "string", description: "list: the `next_cursor` of the last page" },
3034 },
31 required: ["repo"],
3235 },
3336 writes: true,
3437 heldNotWhen: (args) => args["action"] !== "share" && args["action"] !== "unshare",
3538 async run(ctx, user, args) {
39 if (args["action"] === "saved") {
40 const remove = args["remove"];
41 if (typeof remove === "string") return removeSaved(ctx.app.db, user.id, remove) ? good({ says: "Saved search removed; no trace was touched." }) : bad("not_found", "no such saved search of yours");
42 if (args["name"] !== undefined || args["query"] !== undefined) {
43 if (cleanName(args["name"]) === undefined) return bad("bad_name", SAVE_WORDS.bad_name);
44 const made = saveSearch(ctx.app.db, user.id, args["name"], typeof args["query"] === "string" ? args["query"].replace(/^\?/, "").slice(0, 2000) : "");
45 return made.ok ? good({ saved: { ...openSaved(made.value), filter: undefined } }) : bad(made.error, SAVE_WORDS[made.error]);
46 }
47 return good({ items: openedSaved(ctx.app.db, user.id).map((o) => ({ id: o.id, name: o.name, query: o.query, href: o.href, dropped: o.dropped })) });
48 }
3649 const repo = repoArg(ctx, user, args);
3750 if (isAnswer(repo)) return repo;
3851 const run = args["run"];
src/http/routes/operations.ts +3
@@ -26,6 +26,7 @@ import { tracePage, traceStep } from "../../web/pages/trace.ts";
2626 import { traceComparePage } from "../../web/pages/trace_compare.ts";
2727 import { traceShare, traceShared, traceUnshare } from "../../web/pages/trace_share.ts";
2828 import { tracesPage } from "../../web/pages/traces.ts";
29 import { traceSave, traceSavedRemove } from "../../web/pages/traces_saved.ts";
2930 import { oauthCallbackUri } from "../api.ts";
3031 import { gamesRoutes } from "../games_routes.ts";
3132 import { infraRoutes } from "../infra_routes.ts";
@@ -124,6 +125,8 @@ export function operationsRoutes(router: Router<Handler>, knownPatterns: () => s
124125 router.add("GET", "/runs/:id", runRedirect);
125126 // A crew run as a tree of steps (#17993). Literal, above /:owner.
126127 router.add("GET", "/traces", tracesPage);
128 router.add("POST", "/traces/saved", traceSave);
129 router.add("POST", "/traces/saved/:id/remove", traceSavedRemove);
127130 router.add("GET", "/traces/:id", tracePage);
128131 router.add("GET", "/traces/:id/steps/:n", traceStep);
129132 // Two runs of one issue side by side, and a trace shared by a link its owner made (#17995).
src/trace/saved.ts added +97
@@ -0,0 +1,97 @@
1 /**
2 * A person's saved /traces searches (#18369): a name and the query string the list takes, at most
3 * 50 a person, private to them (every read and write is keyed by the user id, so another person's
4 * id is a miss, not a refusal that proves it exists). The query is stored in `filterQuery`'s fixed
5 * order, without a page cursor, and read again through `readFilter` on every open: a facet that no
6 * longer exists is dropped and `openSaved` names what was dropped. Plain data in, plain data out.
7 */
8 import type { Database } from "bun:sqlite";
9 import { id as newId } from "../kernel/id.ts";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import { filterQuery, readFilter, type TraceFilter } from "./list.ts";
12
13 export const MAX_SAVED = 50;
14 export const SAVED_ID = /^[0-9A-Za-z_-]{1,64}$/;
15 /** A name is one line of 1 to 60 characters with no control character. */
16 export const NAME_MAX = 60;
17
18 export interface SavedSearch {
19 readonly id: string;
20 readonly name: string;
21 /** The stored query string, `?`-less. */
22 readonly query: string;
23 }
24
25 /** A saved search as opened: the link and what the stored query had that no longer holds. */
26 export interface OpenedSearch extends SavedSearch {
27 readonly href: string;
28 readonly filter: TraceFilter;
29 readonly dropped: readonly string[];
30 }
31
32 export type SaveError = "bad_name" | "empty_search" | "limit_reached";
33
34 /** What a refusal says, in the words every door shares. */
35 export const SAVE_WORDS: Record<SaveError, string> = {
36 bad_name: `a name is 1 to ${NAME_MAX} characters on one line`,
37 empty_search: "there is nothing to save: set a search or a filter first",
38 limit_reached: `you already keep ${MAX_SAVED} saved searches: remove one to save another`,
39 };
40
41 export const cleanName = (raw: unknown): string | undefined => {
42 if (typeof raw !== "string") return undefined;
43 const s = raw.trim().replace(/\s+/g, " ");
44 return s.length >= 1 && [...s].length <= NAME_MAX && !/[\u0000-\u001f\u007f]/.test(s) ? s : undefined;
45 };
46
47 /** The canonical `?`-less query of whatever string was sent: validated, ordered, no cursor. */
48 export const canonicalQuery = (raw: string): string => filterQuery(readFilter(new URLSearchParams(raw)), { before: undefined }).slice(1);
49
50 export function listSaved(db: Database, userId: string): SavedSearch[] {
51 return db.query<SavedSearch, [string]>("SELECT id, name, query FROM trace_saved WHERE user_id = ?1 ORDER BY name COLLATE NOCASE, id").all(userId);
52 }
53
54 /**
55 * Save the search under the name; the same name again, in any letter case, replaces its query (and
56 * takes the new casing).
57 */
58 export function saveSearch(db: Database, userId: string, rawName: unknown, rawQuery: string, now = Date.now()): Result<SavedSearch, SaveError> {
59 const name = cleanName(rawName);
60 if (name === undefined) return err("bad_name");
61 const query = canonicalQuery(rawQuery);
62 if (query === "") return err("empty_search");
63 return db.transaction((): Result<SavedSearch, SaveError> => {
64 const had = db.query<{ id: string }, [string, string]>("SELECT id FROM trace_saved WHERE user_id = ?1 AND name = ?2 COLLATE NOCASE").get(userId, name);
65 if (had !== null) {
66 db.query("UPDATE trace_saved SET query = ?2, name = ?3 WHERE id = ?1").run(had.id, query, name);
67 return ok({ id: had.id, name, query });
68 }
69 const n = db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM trace_saved WHERE user_id = ?1").get(userId)?.n ?? 0;
70 if (n >= MAX_SAVED) return err("limit_reached");
71 const id = newId(now);
72 db.query("INSERT INTO trace_saved (id, user_id, name, query, created_at) VALUES (?1, ?2, ?3, ?4, ?5)").run(id, userId, name, query, new Date(now).toISOString());
73 return ok({ id, name, query });
74 })();
75 }
76
77 /**
78 * Remove the person's own saved search; false when it is not theirs or not there. Traces untouched.
79 */
80 export function removeSaved(db: Database, userId: string, id: string): boolean {
81 return SAVED_ID.test(id) && db.query("DELETE FROM trace_saved WHERE id = ?1 AND user_id = ?2").run(id, userId).changes > 0;
82 }
83
84 /** Read the stored query again: what still parses is the filter; what does not is named. */
85 export function openSaved(s: SavedSearch): OpenedSearch {
86 const asked = new URLSearchParams(s.query);
87 const filter = readFilter(asked);
88 const kept = new URLSearchParams(filterQuery(filter));
89 const dropped = [...new Set(asked.keys())].filter((k) => k !== "before" && !kept.has(k)).sort();
90 return { ...s, filter, dropped, href: `/traces${filterQuery(filter, { before: undefined })}` };
91 }
92
93 export const savedWords = (o: OpenedSearch): string => (o.dropped.length === 0 ? "" : `${o.dropped.join(", ")} no longer ${o.dropped.length === 1 ? "holds" : "hold"} and was dropped`);
94
95 export function openedSaved(db: Database, userId: string): OpenedSearch[] {
96 return listSaved(db, userId).map(openSaved);
97 }
src/tui/screens/traces.ts +47 −5
@@ -7,13 +7,17 @@
77 * `j`/`k` move, Enter opens the run's trace, `n` reads the next older page. `v` marks a row (two at
88 * most, the older mark drops) and `d` opens the two as a comparison (#18085): the trace screen's
99 * own, so the page's words; two runs of different issues are told so. Every value goes through the
10 * page's own `readFilter`. Read-only; Esc closes. The lines are `traceLine`, the page's own row.
10 * page's own `readFilter`. `b` types the name of a saved search (the page's links) and opens the
11 * first that starts with it, `w` names the filters on screen and keeps them, `x` removes the saved
12 * search last opened (the search only: no trace is touched); a facet a saved search holds that no
13 * longer exists is dropped and said. Esc closes. The lines are `traceLine`, the page's own row.
1114 */
1215 import { binding } from "../app/keys.ts";
1316 import type { Ctx, Screen } from "../app/app.ts";
1417 import { listTraces, OUTCOMES, readFilter, SOURCES, traceLine, type TraceFilter, type TraceList } from "../../trace/list.ts";
1518 import { getRepoById } from "../../core/repos.ts";
1619 import { getRun } from "../../core/runs.ts";
20 import { openedSaved, removeSaved, SAVE_WORDS, saveSearch, savedWords, NAME_MAX, type OpenedSearch } from "../../trace/saved.ts";
1721 import { sameIssue } from "../../trace/compare.ts";
1822 import { traceScreen } from "./trace.ts";
1923 import { Scroll, openOnWeb } from "./common.ts";
@@ -38,6 +42,22 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
3842 let at = 0;
3943 // The runs marked to compare, oldest mark first.
4044 let marked: string[] = [];
45 // Typing a saved search's name to open it (`open`) or to keep the filters under it (`save`).
46 let naming: { for: "open" | "save"; text: string } | undefined;
47 let opened: OpenedSearch | undefined;
48 const open = (o: OpenedSearch): void => {
49 for (const k of Object.keys(facet)) delete facet[k as keyof typeof facet];
50 for (const [k, v] of Object.entries(o.filter)) if (k !== "before" && v !== undefined) facet[k as keyof typeof facet] = v;
51 opened = o;
52 before = undefined;
53 read();
54 ctx.toast(o.dropped.length === 0 ? `opened “${o.name}”` : `opened “${o.name}”: ${savedWords(o)}`, o.dropped.length === 0 ? undefined : "attn");
55 };
56 const keep = (name: string): void => {
57 const q = new URLSearchParams(Object.entries(facet).filter((e): e is [string, string] => e[1] !== undefined));
58 const made = saveSearch(f.app.db, f.user!.id, name, q.toString());
59 ctx.toast(made.ok ? `saved “${made.value.name}”` : SAVE_WORDS[made.error], made.ok ? undefined : "attn");
60 };
4161 let typing: "q" | "tool" | "file" | "from" | "to" | undefined;
4262 const read = (): void => {
4363 list = listTraces(f.app, f.user, filter());
@@ -61,11 +81,14 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
6181 };
6282 return {
6383 title: "Traces",
64 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["i", "r", "m", "o", "p"], "kind, repo, model, outcome, person"), binding(["u", "e"], "tool used, file touched"), binding(["f", "t"], "from, to day"), binding(["c"], "clear filters"), binding(["esc"], "close")],
84 keys: [binding(["j", "k"], "move"), binding(["enter"], "open the trace"), binding(["v"], "mark"), binding(["d"], "compare marked"), binding(["n"], "older"), binding(["/"], "search"), binding(["i", "r", "m", "o", "p"], "kind, repo, model, outcome, person"), binding(["u", "e"], "tool used, file touched"), binding(["f", "t"], "from, to day"), binding(["b", "w", "x"], "open, save, remove a saved search"), binding(["c"], "clear filters"), binding(["esc"], "close")],
6585 render(area, s) {
6686 const c = ctx.theme.c;
6787 s.text(area.x, area.y, truncate(`${typing === undefined ? "/ to search" : typing === "q" ? "Search" : typing === "from" ? "From (YYYY-MM-DD)" : typing === "to" ? "To (YYYY-MM-DD)" : typing === "tool" ? "Tool (Edit, Bash…)" : "File (path)"}: ${typing === undefined || typing === "q" ? (facet.q ?? "") : (facet[typing] ?? "")}${typing === undefined ? "" : "_"}${summary()}`, area.w), style(c.fg, c.bg), area.x + area.w);
68 if (list.unindexed > 0) s.text(area.x, area.y + 1, truncate(`${list.unindexed} not indexed for tools and files yet: a tool or file search may miss them`, area.w), style(c.muted, c.bg), area.x + area.w);
88 if (naming !== undefined) {
89 const match = naming.for === "open" ? openedSaved(f.app.db, f.user!.id).find((o) => o.name.toLowerCase().startsWith(naming!.text.toLowerCase())) : undefined;
90 s.text(area.x, area.y + 1, truncate(naming.for === "open" ? `Open saved search: ${naming.text}_ ${match === undefined ? "(none)" : `→ ${match.name}`}` : `Name this search: ${naming.text}_`, area.w), style(c.fg, c.bg), area.x + area.w);
91 } else if (list.unindexed > 0) s.text(area.x, area.y + 1, truncate(`${list.unindexed} not indexed for tools and files yet: a tool or file search may miss them`, area.w), style(c.muted, c.bg), area.x + area.w);
6992 if (list.rows.length === 0) {
7093 emptyState(s, { ...area, y: area.y + 2, h: Math.max(1, area.h - 2) }, c, { title: Object.keys(facet).length === 0 ? "No traces yet" : "No trace matches", body: "" });
7194 return;
@@ -85,14 +108,33 @@ function tracesScreen(f: Session, ctx: Ctx): Screen {
85108 if (at < scroll.top) scroll.top = at;
86109 else if (at >= scroll.top + scroll.height) scroll.top = at - scroll.height + 1;
87110 };
88 if (typing !== undefined) {
111 if (naming !== undefined) {
112 const n = naming;
113 if (e.key === "esc") naming = undefined;
114 else if (e.key === "enter") {
115 naming = undefined;
116 if (n.for === "save") keep(n.text);
117 else {
118 const hit = openedSaved(f.app.db, f.user!.id).find((o) => o.name.toLowerCase().startsWith(n.text.toLowerCase()));
119 if (hit === undefined) ctx.toast("no saved search by that name", "attn");
120 else open(hit);
121 }
122 } else if (e.key === "backspace") n.text = [...n.text].slice(0, -1).join("");
123 else if (!e.ctrl && !e.alt && [...e.key].length === 1 && [...n.text].length < NAME_MAX) n.text += e.key;
124 } else if (typing !== undefined) {
89125 const cur = facet[typing] ?? "";
90126 if (e.key === "esc" || e.key === "enter") typing = undefined;
91127 else if (e.key === "backspace") set(typing, [...cur].slice(0, -1).join(""));
92128 else if (!e.ctrl && !e.alt && [...e.key].length === 1 && [...cur].length < 80) set(typing, cur + e.key);
93129 } else if (e.key === "esc") ctx.pop();
94130 else if (e.key === "/") typing = "q";
95 else if (e.key === "u") typing = "tool";
131 else if (e.key === "b") naming = { for: "open", text: "" };
132 else if (e.key === "w") naming = { for: "save", text: "" };
133 else if (e.key === "x") {
134 if (opened !== undefined && removeSaved(f.app.db, f.user!.id, opened.id)) ctx.toast(`removed “${opened.name}”: the traces are untouched`);
135 else ctx.toast("open a saved search with b first", "attn");
136 opened = undefined;
137 } else if (e.key === "u") typing = "tool";
96138 else if (e.key === "e") typing = "file";
97139 else if (e.key === "f") typing = "from";
98140 else if (e.key === "t") typing = "to";
src/web/pages/traces.ts +23 −1
@@ -8,6 +8,7 @@
88 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
99 import type { Ctx } from "../../http/context.ts";
1010 import { costWords, filterQuery, listTraces, OUTCOMES, SOURCES, readFilter, type TraceFilter, type TraceList, type TraceRow } from "../../trace/list.ts";
11 import { openedSaved, NAME_MAX, savedWords, type OpenedSearch } from "../../trace/saved.ts";
1112 import { pageHead } from "../chrome.ts";
1213 import { html, type Html } from "../html.ts";
1314 import { page } from "../layout.ts";
@@ -68,6 +69,25 @@ function controls(f: TraceFilter, list: TraceList): Html {
6869 : html`<p class="small" id="traces-active">${active.map(([k, label]) => html`<a href="/traces${filterQuery(f, { [k]: undefined, before: undefined })}" aria-label="Remove ${label}: ${f[k] ?? ""}">${badge(`${label}: ${f[k] ?? ""}`, { variant: "secondary", icon: "x" })}</a> `)}</p>`}`;
6970 }
7071
72 /** The viewer's saved searches as links above the results, and the forms that keep and end them. */
73 function saved(f: TraceFilter, mine: readonly OpenedSearch[], searching: boolean): Html {
74 const keep = html`<form method="post" action="/traces/saved" class="bar small" id="traces-save">
75 <input type="hidden" name="query" value="${filterQuery(f, { before: undefined }).slice(1)}" />
76 <input class="input" name="name" required maxlength="${NAME_MAX}" placeholder="Name this search" aria-label="Name this search" autocomplete="off" />
77 ${btn("Save search", { size: "sm" })}</form>`;
78 return html`${mine.length === 0
79 ? null
80 : html`<nav class="small" id="traces-saved" aria-label="Saved searches">Saved: ${mine.map((s) => html`<a href="${s.href}">${s.name}</a>${s.dropped.length === 0 ? null : html` <span class="muted" data-dropped>(${savedWords(s)})</span>`} `)}</nav>
81 ${disclosure(
82 "Remove a saved search",
83 html`<p class="small muted">Removing deletes the saved search only; no trace is touched.</p>${mine.map(
84 (s) => html`<form method="post" action="/traces/saved/${s.id}/remove" class="bar small">${s.name} ${btn("Remove", { size: "sm", variant: "secondary" })}</form>`,
85 )}`,
86 { small: true, extra: "mt" },
87 )}`}

At 50 saved the form disappears, so the 'limit reached, remove one' reason is never shown and an existing name cannot be replaced. Always render the form; let the POST say why.

88 ${searching ? keep : null}`;
89 }
90
7191 const CSS = `
7292 .traces-search{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-bottom:.5rem}
7393 .traces-search>.input{flex:1 1 14rem;min-width:0}
@@ -85,9 +105,11 @@ export function tracesPage(ctx: Ctx): Response {
85105 const reading = performance.now();
86106 const list = listTraces(ctx.app, ctx.auth.user, f);
87107 notePhase(ctx.request, "read", performance.now() - reading);
108 const mine = ctx.auth.user === undefined ? [] : openedSaved(ctx.app.db, ctx.auth.user.id);
88109 const searching = Object.keys(f).some((k) => k !== "before");
89110 const body = html`${pageHead("Traces", { sub: "Every crew run, Talk turn and imported session you may open, newest first." })}
90111 ${controls(f, list)}
112 ${ctx.auth.user === undefined ? null : saved(f, mine, searching)}
91113 ${list.unindexed === 0
92114 ? null
93115 : html`<p class="small muted" id="traces-unindexed">${list.unindexed} ${list.unindexed === 1 ? "trace is" : "traces are"} not indexed for tools and files yet, so a Tool or File search may miss ${list.unindexed === 1 ? "it" : "them"}.</p>`}
@@ -96,7 +118,7 @@ export function tracesPage(ctx: Ctx): Response {
96118 : html`<div id="traces-list">${listCard(list.rows.map(line))}</div>`}
97119 ${list.next === undefined ? null : html`<p><a class="btn" id="traces-more" href="/traces${filterQuery(f, { before: list.next })}" rel="next">Older traces</a></p>`}`;
98120 const rendering = performance.now();
99 const response = page({ ctx, title: "Traces", body, styleCss: CSS });
121 const response = page({ ctx, title: "Traces", body, styleCss: CSS, palette: mine.map((s) => ({ t: s.name, h: s.href, c: "Saved trace searches" })) });
100122 notePhase(ctx.request, "render", performance.now() - rendering);
101123 return response;
102124 }
src/web/pages/traces_saved.ts added +34
@@ -0,0 +1,34 @@
1 /**
2 * Saved /traces searches (#18369). `POST /traces/saved` keeps the filters in the form under a name
3 * and `POST /traces/saved/:id/remove` ends one: both same-origin forms (`readForm`), both the
4 * signed-in person's own (`trace/saved.ts` keys every row by them). Removing deletes the saved
5 * query only; no trace is touched. The answer goes back to the list, opened on the search.
6 */
7 import type { Ctx } from "../../http/context.ts";
8 import { removeSaved, SAVE_WORDS, saveSearch } from "../../trace/saved.ts";
9 import { forbiddenPage, notFoundPage } from "../chrome.ts";
10 import { readForm } from "../form.ts";
11 import { flashTo } from "../layout.ts";
12
13 // POST /traces/saved
14 export async function traceSave(ctx: Ctx): Promise<Response> {
15 const form = await readForm(ctx, "rw");
16 if (form instanceof Response) return form;
17 const user = ctx.auth.user;
18 if (user === undefined) return forbiddenPage(ctx, "Sign in to save a search.");
19 const name = form.get("name");
20 const query = form.get("query");
21 const made = saveSearch(ctx.app.db, user.id, typeof name === "string" ? name : undefined, typeof query === "string" ? query.slice(0, 2000) : "");
22 if (!made.ok) return flashTo(ctx, `/traces${typeof query === "string" && made.error !== "empty_search" ? `?${new URLSearchParams(query.slice(0, 2000))}` : ""}`, { message: SAVE_WORDS[made.error], tone: "attn" });
23 return flashTo(ctx, `/traces?${made.value.query}`, { message: `Saved “${made.value.name}”.` });
24 }
25
26 // POST /traces/saved/:id/remove
27 export async function traceSavedRemove(ctx: Ctx): Promise<Response> {
28 const form = await readForm(ctx, "rw");
29 if (form instanceof Response) return form;
30 const user = ctx.auth.user;
31 if (user === undefined) return forbiddenPage(ctx, "Sign in to manage saved searches.");
32 if (!removeSaved(ctx.app.db, user.id, ctx.params.id ?? "")) return notFoundPage(ctx);
33 return flashTo(ctx, "/traces", { message: "Saved search removed. The traces are untouched." });
34 }
test/traces-saved.test.ts added +240
@@ -0,0 +1,240 @@
1 /**
2 * Saved /traces searches (#18369): save, list, open, remove, private to the person, 50 at most,
3 * cross-site 403.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createSession } from "../src/core/sessions.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { MAX_SAVED, openSaved, listSaved, saveSearch, removeSaved } from "../src/trace/saved.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { entry } from "../src/tui/screens/traces.ts";
18 import { seedAdmin } from "./helpers/admin.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { settleApp } from "./helpers/tui.ts";
21
22 quietLogs();
23
24 let dir = "";
25 let app: App;
26 let servers: Servers;
27 let alice: User;
28 let bob: User;
29 let at = "";
30 let bt = "";
31
32 const api = (token: string, path: string, init: RequestInit = {}) =>
33 fetch(`${servers.url}${path}`, { ...init, headers: { authorization: `Bearer ${token}`, "content-type": "application/json", ...(init.headers as object) } });
34 const form = (token: string, path: string, fields: Record<string, string>, headers: Record<string, string> = {}) =>
35 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { authorization: `Bearer ${token}`, ...headers }, body: new URLSearchParams(fields) });
36
37 beforeAll(async () => {
38 dir = await mkdtemp(join(tmpdir(), "forge-traces-saved-"));
39 app = createApp({ dataDir: dir, port: 0 });
40 servers = await serve(app);
41 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
42 if (!a.ok) throw new Error(a.error);
43 alice = a.value;
44 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
45 if (!b.ok) throw new Error("bob");
46 bob = b.value;
47 at = createToken(app.db, alice.id, "t", "rw").token;
48 bt = createToken(app.db, bob.id, "t", "rw").token;
49 }, 30_000);
50 afterAll(async () => {
51 servers.stop();
52 app.close();
53 await rm(dir, { recursive: true, force: true });
54 });
55
56 test("save, list, open and remove over the API; the name is stored as given and the query in the list's order", async () => {
57 const made = await api(at, "/api/v1/traces/saved", { method: "POST", body: JSON.stringify({ name: "Failed <b>runs</b>", query: "?outcome=failed&repo=alice/lamp&before=zzz" }) });
58 expect(made.status).toBe(201);
59 const one = (await made.json()) as { id: string; name: string; query: string; href: string; dropped: string[] };
60 expect(one.query).toBe("repo=alice%2Flamp&outcome=failed");
61 expect(one.href).toBe("/traces?repo=alice%2Flamp&outcome=failed");
62 const list = (await (await api(at, "/api/v1/traces/saved")).json()) as { items: { id: string }[] };
63 expect(list.items.map((i) => i.id)).toEqual([one.id]);
64 // The same name again replaces the query rather than adding one.
65 await api(at, "/api/v1/traces/saved", { method: "POST", body: JSON.stringify({ name: "Failed <b>runs</b>", query: "outcome=ok" }) });
66 expect(listSaved(app.db, alice.id).map((s) => s.query)).toEqual(["outcome=ok"]);
67 const gone = await api(at, `/api/v1/traces/saved/${one.id}`, { method: "DELETE" });
68 expect(gone.status).toBe(200);
69 expect(listSaved(app.db, alice.id)).toEqual([]);
70 expect((await api(at, `/api/v1/traces/saved/${one.id}`, { method: "DELETE" })).status).toBe(404);
71 });
72
73 test("a name is escaped on the page and a saved link opens the list", async () => {
74 expect((await form(at, "/traces/saved", { name: "Failed <b>runs</b>", query: "outcome=failed" })).status).toBe(303);
75 const page = await (await fetch(`${servers.url}/traces`, { headers: { authorization: `Bearer ${at}` } })).text();
76 expect(page).toContain('id="traces-saved"');
77 expect(page).toContain("Failed &lt;b&gt;runs&lt;/b&gt;");
78 expect(page).not.toContain("<b>runs</b>");
79 expect(page).toContain('href="/traces?outcome=failed"');
80 expect(page).toContain("no trace is touched");
81 });
82
83 test("another person neither sees nor removes it", async () => {
84 const mine = listSaved(app.db, alice.id)[0]!;
85 expect(listSaved(app.db, bob.id)).toEqual([]);
86 expect(((await (await api(bt, "/api/v1/traces/saved")).json()) as { items: unknown[] }).items).toEqual([]);
87 expect((await api(bt, `/api/v1/traces/saved/${mine.id}`, { method: "DELETE" })).status).toBe(404);
88 expect((await form(bt, `/traces/saved/${mine.id}/remove`, {})).status).toBe(404);
89 expect(removeSaved(app.db, bob.id, mine.id)).toBe(false);
90 expect(await (await fetch(`${servers.url}/traces`, { headers: { authorization: `Bearer ${bt}` } })).text()).not.toContain("traces-saved");
91 expect(listSaved(app.db, alice.id)).toHaveLength(1);
92 });
93
94 test("a cross-site form is refused and nothing is saved or removed", async () => {
95 const mine = listSaved(app.db, alice.id)[0]!;
96 expect((await form(at, "/traces/saved", { name: "x", query: "outcome=ok" }, { origin: "https://evil.example" })).status).toBe(403);
97 expect((await form(at, `/traces/saved/${mine.id}/remove`, {}, { origin: "https://evil.example" })).status).toBe(403);
98 expect(listSaved(app.db, alice.id)).toHaveLength(1);
99 expect((await form(at, `/traces/saved/${mine.id}/remove`, {})).status).toBe(303);
100 expect(listSaved(app.db, alice.id)).toHaveLength(0);
101 });
102
103 test("the 51st is refused and says why; an empty search or a bad name is refused too", async () => {
104 for (let i = 0; i < MAX_SAVED; i++) expect(saveSearch(app.db, alice.id, `s${i}`, "outcome=ok").ok).toBe(true);
105 const over = await api(at, "/api/v1/traces/saved", { method: "POST", body: JSON.stringify({ name: "one more", query: "outcome=ok" }) });
106 expect(over.status).toBe(422);
107 const said = (await over.json()) as { error: string; message: string };
108 expect(said.error).toBe("limit_reached");
109 expect(said.message).toContain("50 saved searches");
110 expect(listSaved(app.db, alice.id)).toHaveLength(MAX_SAVED);
111 // Bob's own count is his.
112 expect(saveSearch(app.db, bob.id, "mine", "outcome=ok").ok).toBe(true);
113 const empty = await api(bt, "/api/v1/traces/saved", { method: "POST", body: JSON.stringify({ name: "n", query: "before=abc" }) });
114 expect(((await empty.json()) as { error: string }).error).toBe("empty_search");
115 expect((await api(bt, "/api/v1/traces/saved", { method: "POST", body: JSON.stringify({ name: " ", query: "outcome=ok" }) })).status).toBe(422);
116 const flash = await form(at, "/traces/saved", { name: "one more", query: "outcome=ok" });
117 expect(flash.status).toBe(303);
118 expect(listSaved(app.db, alice.id)).toHaveLength(MAX_SAVED);
119 for (const s of listSaved(app.db, alice.id)) removeSaved(app.db, alice.id, s.id);
120 });
121
122 test("a saved query is read again on open: a facet that no longer exists is dropped, and said", () => {
123 const o = openSaved({ id: "x", name: "old", query: "outcome=exploded&repo=alice%2Flamp&kind=run" });
124 expect(o.dropped).toEqual(["outcome"]);
125 expect(o.href).toBe("/traces?kind=run&repo=alice%2Flamp");
126 });
127
128 test("the MCP trace tool's saved action keeps, lists and removes, for the caller alone", async () => {
129 const call = async (token: string, args: unknown) => {
130 const r = await fetch(`${servers.url}/mcp`, {
131 method: "POST",
132 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
133 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "trace", arguments: args } }),
134 });
135 const text: string = ((await r.json()) as any).result.content[0].text;
136 try {
137 return JSON.parse(text);
138 } catch {
139 return text;
140 }
141 };
142 const kept = await call(at, { action: "saved", name: "models", query: "model=opus" });
143 expect(kept.saved.href).toBe("/traces?model=opus");
144 const items = (await call(at, { action: "saved" })).items as { id: string }[];
145 expect(items).toHaveLength(1);
146 expect((await call(bt, { action: "saved" })).items.map((i: { name: string }) => i.name)).toEqual(["mine"]);
147 expect(await call(bt, { action: "saved", remove: items[0]!.id })).toContain("no such saved search");
148 expect(JSON.stringify(await call(at, { action: "saved", remove: items[0]!.id }))).toContain("removed");
149 });
150
151 test("the terminal opens a saved search by the start of its name, saves the filters, and removes it", async () => {
152 saveSearch(app.db, alice.id, "Failures", "outcome=failed&repo=nope%20bad");
153 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice }, { terminal: headlessTerminal(120, 30), exitHooks: false });
154 tui.start();
155 await settleApp(tui);
156 entry.run(session, tui.ctx);
157 await settleApp(tui);
158 const press = async (key: string): Promise<string> => {
159 tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
160 await settleApp(tui);
161 return tui.screen.toText();
162 };
163 for (const k of "bfai") await press(k);
164 const shown = await press("l");
165 expect(shown).toContain("Open saved search: fail");
166 expect(shown).toContain("Failures");
167 await press("enter");
168 expect(tui.screen.toText()).toContain("outcome=failed");
169 await press("w");
170 for (const k of "Again") await press(k);
171 await press("enter");
172 expect(listSaved(app.db, alice.id).map((s) => s.name).sort()).toEqual(["Again", "Failures"]);
173 await press("b");
174 for (const k of "Fail") await press(k);
175 await press("enter");
176 await press("x");
177 expect(listSaved(app.db, alice.id).map((s) => s.name)).toEqual(["Again"]);
178 tui.stop();
179 });
180
181 const clearAlice = () => { for (const s of listSaved(app.db, alice.id)) removeSaved(app.db, alice.id, s.id); };
182
183 test("the page keeps the Save form at the limit and a refusal says why; an existing name still replaces", async () => {
184 clearAlice();
185 for (let i = 0; i < MAX_SAVED; i++) expect(saveSearch(app.db, alice.id, `s${i}`, "outcome=ok").ok).toBe(true);
186 const page = await (await fetch(`${servers.url}/traces?outcome=failed`, { headers: { authorization: `Bearer ${at}` } })).text();
187 expect(page).toContain('id="traces-save"');
188 expect(saveSearch(app.db, alice.id, "S3", "outcome=failed").ok).toBe(true);
189 expect(listSaved(app.db, alice.id)).toHaveLength(MAX_SAVED);
190 for (const s of listSaved(app.db, alice.id)) removeSaved(app.db, alice.id, s.id);
191 });
192
193 test("names are one name whatever their letter case", () => {
194 clearAlice();
195 const a = saveSearch(app.db, alice.id, "Failures", "outcome=failed");
196 const b = saveSearch(app.db, alice.id, "failures", "outcome=ok");
197 expect(a.ok && b.ok && a.value.id === b.value.id).toBe(true);
198 expect(listSaved(app.db, alice.id).map((s) => [s.name, s.query])).toEqual([["failures", "outcome=ok"]]);
199 for (const s of listSaved(app.db, alice.id)) removeSaved(app.db, alice.id, s.id);
200 });
201
202 test("the page says what a saved facet dropped, and the palette lists the viewer's saved searches only", async () => {
203 clearAlice();
204 app.db.query("INSERT INTO trace_saved (id, user_id, name, query, created_at) VALUES ('old1', ?1, 'Old one', 'outcome=exploded&kind=run', ?2)").run(alice.id, new Date().toISOString());
205 const page = await (await fetch(`${servers.url}/traces`, { headers: { authorization: `Bearer ${at}` } })).text();
206 expect(page).toContain("data-dropped");
207 expect(page).toContain("outcome no longer holds and was dropped");
208 const index = (html: string) => JSON.parse(/<script type="application\/json" id="palette-index">([\s\S]*?)<\/script>/.exec(html)![1]!.replace(/\\u003c/g, "<")) as unknown;
209 expect(JSON.stringify(index(page))).toContain('"c":"Saved trace searches"');
210 const theirs = await (await fetch(`${servers.url}/traces`, { headers: { authorization: `Bearer ${bt}` } })).text();
211 expect(JSON.stringify(index(theirs))).not.toContain("Old one");
212 removeSaved(app.db, alice.id, "old1");
213 });
214
215 test("a browser session's cross-origin POST and DELETE on the API are refused", async () => {
216 clearAlice();
217 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
218 const kept = saveSearch(app.db, alice.id, "keep", "outcome=ok");
219 if (!kept.ok) throw new Error("save");
220 const evil = { cookie, origin: "https://evil.example", "content-type": "application/json" };
221 const post = await fetch(`${servers.url}/api/v1/traces/saved`, { method: "POST", headers: evil, body: JSON.stringify({ name: "x", query: "outcome=ok" }) });
222 expect(post.status).toBe(403);
223 const del = await fetch(`${servers.url}/api/v1/traces/saved/${kept.value.id}`, { method: "DELETE", headers: evil });
224 expect(del.status).toBe(403);
225 expect(listSaved(app.db, alice.id).map((s) => s.name)).toEqual(["keep"]);
226 removeSaved(app.db, alice.id, kept.value.id);
227 });
228
229 test("the MCP trace tool refuses the 51st saved search in the shared words", async () => {
230 clearAlice();
231 for (let i = 0; i < MAX_SAVED; i++) expect(saveSearch(app.db, alice.id, `m${i}`, "outcome=ok").ok).toBe(true);
232 const r = await fetch(`${servers.url}/mcp`, {
233 method: "POST",
234 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${at}` },
235 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "trace", arguments: { action: "saved", name: "one more", query: "outcome=ok" } } }),
236 });
237 expect(JSON.stringify(await r.json())).toContain("remove one to save another");
238 expect(listSaved(app.db, alice.id)).toHaveLength(MAX_SAVED);
239 for (const s of listSaved(app.db, alice.id)) removeSaved(app.db, alice.id, s.id);
240 });

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

Keyboard shortcuts

Docs