Public: anyone can read this; the crew can change it.
An imported session's page has a red Delete that asks for its title typed #18421
Closed 3h 6m ago
mason/forge:mason/18389-an-imported-session-s-page-has-a-red-del → main 2 commits fork
11 files
changed +259
−5
- docs/design/areas/traces.md
- docs/features/traces.md
- src/actions/trace_delete.ts
- src/http/lazy_lists.ts
- src/http/routes/operations.ts
- src/tui/screens/traces.ts
- src/web/pages/trace_delete.ts
- src/web/pages/trace_delete_form.ts
- src/web/pages/trace_imported.ts
- test/trace-imported-delete.test.ts
- test/tui-asks-first.test.ts
docs/design/areas/traces.md +2
| @@ -5,3 +5,5 @@ | ||
| 5 | 5 | `/traces` (`src/web/pages/traces.ts`), the list. Page-local classes, drawn from existing tokens: `.traces-search` (the search form: the input grows, the button and the Filters disclosure wrap under it on a phone) and `.traces-facets` (the facet selects and dates, an auto-fit grid of `.field`s). `#traces-list` only ellipsises a row's title and meta to one line each. A removable active filter is the shared `.badge` with the `x` icon inside its link. |
| 6 | 6 | |
| 7 | 7 | `/traces/:id/compare/:other` (`src/web/pages/trace_compare.ts`) is one `table` of the shared table class, A and B as column heads and B − A last; `/traces/shared/:token` (`src/web/pages/trace_share.ts`) is the same `details` rows with the raw lines inline and no script. No new classes. |
| 8 | ||
| 9 | An imported session's page (`src/web/pages/trace_imported.ts`) ends its header with `.trace-delete` (`src/web/pages/trace_delete_form.ts`): a `details` whose summary is the shared danger button (small), closed on first paint so nothing shifts, holding one form (the shared field asking for the title typed, then the danger `btn`). It opens by itself, with the reason under the field, after a refused title. No new tokens. |
docs/features/traces.md +1 −1
| @@ -58,7 +58,7 @@ For Codex, point the same command at a rollout: `--data-binary @"$(ls -t ~/.code | ||
| 58 | 58 | |
| 59 | 59 | A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter.ts`, see `import_claude_code.ts`) and one line in `ADAPTERS`; Codex rollouts are taken the same way (`import_codex.ts`). |
| 60 | 60 | |
| 61 | `DELETE /api/v1/traces/<id>` (#18388) deletes one imported session, with `{ "confirm": "<the session's title>" }` as its body (at most 4 KiB; `traceDelete` in `src/kernel/body_caps.ts`). Nothing is removed unless the title is sent exactly: a wrong or missing one is a 422 (`name_mismatch`) and the file and rows stay. Only the importer may: another person's or an unknown id is a 404, a crew run or Talk turn is a 403 (`record_kept`, its record is kept), a session caller's cross-origin request is a 403, and a session with a live share link is a 409 (`shared`: stop sharing first). A right name removes `traces/imported/<id>.jsonl.gz`, the index row and its touched tools and files (`deleteImported` in `src/trace/import.ts`), frees the quota, and answers `{ removed, title, bytes }`. Not yet: a button on the page and a terminal screen. | |
| 61 | `DELETE /api/v1/traces/<id>` (#18388) deletes one imported session, with `{ "confirm": "<the session's title>" }` as its body (at most 4 KiB; `traceDelete` in `src/kernel/body_caps.ts`). Nothing is removed unless the title is sent exactly: a wrong or missing one is a 422 (`name_mismatch`) and the file and rows stay. Only the importer may: another person's or an unknown id is a 404, a crew run or Talk turn is a 403 (`record_kept`, its record is kept), a session caller's cross-origin request is a 403, and a session with a live share link is a 409 (`shared`: stop sharing first). A right name removes `traces/imported/<id>.jsonl.gz`, the index row and its touched tools and files (`deleteImported` in `src/trace/import.ts`), frees the quota, and answers `{ removed, title, bytes }`. The page and the terminal do it too (#18389): on `/traces/<id>` of an imported session, for its importer only, a red **Delete this session** disclosure (a `details`, no script, so nothing shifts) says what is lost and that a live share link must be stopped first, and asks for the title typed exactly; the field's `pattern` is the title, so a browser holds the button back until it matches, and a plain click removes nothing. It posts same-origin to `POST /traces/<id>/delete` (`src/web/pages/trace_delete.ts`, form in `src/web/pages/trace_delete_form.ts`), which checks the title again through `deleteImportedSession` (`src/actions/trace_delete.ts`: the page's reader, the API's remover). A right title lands on `/traces` with a receipt (what was removed, how many bytes); a wrong one, or a live link, draws the page again (422) with why. A crew run or Talk turn shows no control and its post is the not-found. In the terminal's trace list (`src/tui/screens/traces.ts`, the door of both pages above) `D` on an imported session asks for its title in a prompt and deletes on the exact one. | |
| 62 | 62 | |
| 63 | 63 | `/traces/<id>` of an imported trace (#18357) is the same tree and strip a crew run has, read from the stored file (`src/trace/imported_read.ts`, `src/web/pages/trace_imported.ts`), with `#step-N` permalinks and each step's raw lines (the file's lines that name it) on demand at `/traces/<id>/steps/<n>`. Only the importer reads it; anyone else gets the not-found an unknown id gets. Each step line shows the tokens its file held for it (`5 in, 7 cached, 9 out`; a reply split across records is counted once) and the total is their sum; a session holds no cost, and sometimes no tokens: the page says "not recorded in this file" rather than zero. Steps are capped at 20,000. `GET /api/v1/traces/<id>` answers the same tree for an imported id. |
| 64 | 64 | ## One trace as a tree (#18022) |
src/actions/trace_delete.ts added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | /** | |
| 2 | * Deleting an imported session, as a person does it (#18389): the page and the terminal both come | |
| 3 | * through here. The reader is the page's own (`seenTraceRow`: the importer alone; another person's, | |
| 4 | * a crew run's or an unknown id is `not_found`) and the remover is the API's (`deleteImported`), | |
| 5 | * which checks the exact title and a live share link again. | |
| 6 | */ | |
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { User } from "../core/users.ts"; | |
| 9 | import { deleteImported } from "../trace/import.ts"; | |
| 10 | import { seenTraceRow } from "../trace/tree.ts"; | |
| 11 | ||
| 12 | export type Deleted = | |
| 13 | | { readonly ok: true; readonly title: string; readonly bytes: number } | |
| 14 | | { readonly ok: false; readonly error: "not_found" | "name_mismatch" | "shared" }; | |
| 15 | ||
| 16 | /** Remove `id` for `actor` when `confirm` is its exact title. */ | |
| 17 | export function deleteImportedSession(app: App, actor: User | undefined, id: string, confirm: unknown): Deleted { | |
| 18 | const row = actor === undefined ? undefined : seenTraceRow(app, actor, id); | |
| 19 | if (actor === undefined || row?.kind !== "imported") return { ok: false, error: "not_found" }; | |
| 20 | return deleteImported(app.db, app.config.dataDir, actor.id, row.id, confirm); | |
| 21 | } | |
| 22 | ||
| 23 | /** The receipt line: what was removed and what it freed. */ | |
| 24 | export function receiptWords(title: string, bytes: number): string { | |
| 25 | return `Deleted “${title}”: its file and index rows are gone, ${bytes.toLocaleString("en-US")} bytes freed.`; | |
| 26 | } | |
| 27 | ||
| 28 | /** What each refusal tells the person. */ | |
| 29 | export const REFUSALS = { | |
| 30 | not_found: "That session is gone or is not yours.", | |
| 31 | name_mismatch: "That is not the session's exact title: nothing was deleted.", | |
| 32 | shared: "This session has a live share link: stop sharing it first, then delete it.", | |
| 33 | } as const; |
src/http/lazy_lists.ts +1
src/http/routes/operations.ts +2
| @@ -24,6 +24,7 @@ import { resiliencePage, nightlyOutputPage } from "../../web/pages/resilience.ts | ||
| 24 | 24 | import { runRedirect } from "../../web/pages/runs.ts"; |
| 25 | 25 | import { tracePage, traceStep } from "../../web/pages/trace.ts"; |
| 26 | 26 | import { traceComparePage } from "../../web/pages/trace_compare.ts"; |
| 27 | import { traceDelete } from "../../web/pages/trace_delete.ts"; | |
| 27 | 28 | import { traceShare, traceShared, traceUnshare } from "../../web/pages/trace_share.ts"; |
| 28 | 29 | import { tracesPage } from "../../web/pages/traces.ts"; |
| 29 | 30 | import { traceImport } from "../../web/pages/trace_import.ts"; |
| @@ -135,5 +136,6 @@ export function operationsRoutes(router: Router<Handler>, knownPatterns: () => s | ||
| 135 | 136 | router.add("GET", "/traces/:id/compare/:other", traceComparePage); |
| 136 | 137 | router.add("POST", "/traces/:id/share", traceShare); |
| 137 | 138 | router.add("POST", "/traces/:id/unshare", traceUnshare); |
| 139 | router.add("POST", "/traces/:id/delete", traceDelete); | |
| 138 | 140 | router.add("GET", "/traces/shared/:token", traceShared); |
| 139 | 141 | } |
src/tui/screens/traces.ts +28 −4
| @@ -11,7 +11,8 @@ | ||
| 11 | 11 | * first that starts with it, `w` names the filters on screen and keeps them, `x` removes the saved |
| 12 | 12 | * search last opened (the search only: no trace is touched); a facet a saved search holds that no |
| 13 | 13 | * longer exists is dropped and said. On an imported session `s` makes its share link (shown once; |
| 14 | * a second press confirms when one is live, as it ends the old) and `z` ends it (#18377). Esc | |
| 14 | * a second press confirms when one is live, as it ends the old) and `z` ends it (#18377). `D` | |
| 15 | * deletes an imported session after its exact title is typed (#18389), the page's own gate. Esc | |
| 15 | 16 | * closes. The lines are `traceLine`, the page's own row. |
| 16 | 17 | */ |
| 17 | 18 | import { binding } from "../app/keys.ts"; |
| @@ -23,7 +24,8 @@ import { openedSaved, removeSaved, SAVE_WORDS, saveSearch, savedWords, NAME_MAX, | ||
| 23 | 24 | import { sameIssue } from "../../trace/compare.ts"; |
| 24 | 25 | import { traceScreen } from "./trace.ts"; |
| 25 | 26 | import { importedSharedNow, sharedHref, shareImported, unshareImported } from "../../actions/trace_share.ts"; |
| 26 | import { Scroll, openOnWeb } from "./common.ts"; | |
| 27 | import { deleteImportedSession, receiptWords, REFUSALS } from "../../actions/trace_delete.ts"; | |
| 28 | import { Scroll, openOnWeb, promptScreen } from "./common.ts"; | |
| 27 | 29 | import { style } from "../term/style.ts"; |
| 28 | 30 | import { truncate } from "../term/width.ts"; |
| 29 | 31 | import { emptyState } from "../ui/widgets.ts"; |
| @@ -83,9 +85,9 @@ function tracesScreen(f: Session, ctx: Ctx): Screen { | ||
| 83 | 85 | const held = marked.length === 0 ? "" : ` marked ${marked.length}/2 (*)`; |
| 84 | 86 | return `${on.length === 0 ? "" : ` [${on.map(([k, v]) => `${k}=${v}`).join(" ")}]`}${held}`; |
| 85 | 87 | }; |
| 86 | return { | |
| 88 | const screen: Screen = { | |
| 87 | 89 | title: "Traces", |
| 88 | 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(["y"], "import a session on the web"), binding(["s", "z"], "share an imported session, stop sharing"), binding(["c"], "clear filters"), binding(["esc"], "close")], | |
| 90 | 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(["y"], "import a session on the web"), binding(["s", "z"], "share an imported session, stop sharing"), binding(["D"], "delete an imported session (type its title)"), binding(["c"], "clear filters"), binding(["esc"], "close")], | |
| 89 | 91 | render(area, s) { |
| 90 | 92 | const c = ctx.theme.c; |
| 91 | 93 | 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); |
| @@ -176,6 +178,27 @@ function tracesScreen(f: Session, ctx: Ctx): Screen { | ||
| 176 | 178 | else ctx.toast(done.value.was ? "sharing stopped: the link no longer works" : "this session was not shared", "success"); |
| 177 | 179 | } |
| 178 | 180 | if (e.key === "z") confirmShare = undefined; |
| 181 | } else if (e.key === "D") { | |
| 182 | const r = list.rows[at]; | |
| 183 | if (r === undefined || r.kind !== "imported") ctx.toast("delete is for an imported session of yours: move to one", "attn"); | |
| 184 | else { | |
| 185 | const id = r.id; | |
| 186 | ctx.push( | |
| 187 | promptScreen(ctx, screen, { | |
| 188 | title: "Delete this session", | |
| 189 | label: "Type its title to confirm", | |
| 190 | hint: `${r.title} · removes the stored file for good; a live share link must be stopped first`, | |
| 191 | onSubmit: (typed) => { | |
| 192 | const done = deleteImportedSession(f.app, f.user, id, typed); | |
| 193 | if (!done.ok) return REFUSALS[done.error]; | |
| 194 | ctx.toast(receiptWords(done.title, done.bytes), "success"); | |
| 195 | read(); | |
| 196 | ctx.invalidate(); | |
| 197 | return undefined; | |
| 198 | }, | |
| 199 | }), | |
| 200 | ); | |
| 201 | } | |
| 179 | 202 | } else if (e.key === "c") { |
| 180 | 203 | for (const k of Object.keys(facet)) delete facet[k as keyof typeof facet]; |
| 181 | 204 | before = undefined; |
| @@ -190,6 +213,7 @@ function tracesScreen(f: Session, ctx: Ctx): Screen { | ||
| 190 | 213 | return true; |
| 191 | 214 | }, |
| 192 | 215 | }; |
| 216 | return screen; | |
| 193 | 217 | } |
| 194 | 218 | |
| 195 | 219 | export const entry: PaletteEntry = { |
src/web/pages/trace_delete.ts added +25
| @@ -0,0 +1,25 @@ | ||
| 1 | /** | |
| 2 | * POST /traces/:id/delete (#18389): the form on an imported session's page. Same-origin | |
| 3 | * (`readForm`), the importer alone (`deleteImportedSession`, which reads the row as the page does | |
| 4 | * and removes it as the API does). A right title lands on `/traces` with a receipt; a wrong one, or | |
| 5 | * a live share link, draws the session's page again (422) with why and the title kept. Anyone | |
| 6 | * else, a crew run or an unknown id gets the not-found a missing page gets. | |
| 7 | */ | |
| 8 | import { deleteImportedSession, receiptWords, REFUSALS } from "../../actions/trace_delete.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { notFoundPage } from "../chrome.ts"; | |
| 11 | import { asRefusal, field, readForm, refused, refuseHere } from "../form.ts"; | |
| 12 | import { flashTo } from "../layout.ts"; | |
| 13 | import { importedRowOf, importedTracePage } from "./trace_imported.ts"; | |
| 14 | ||
| 15 | export async function traceDelete(ctx: Ctx): Promise<Response> { | |
| 16 | const form = await readForm(ctx, "rw"); | |
| 17 | if (form instanceof Response) return form; | |
| 18 | const row = importedRowOf(ctx); | |
| 19 | if (row === undefined) return notFoundPage(ctx); | |
| 20 | const done = deleteImportedSession(ctx.app, ctx.auth.user, row.id, field(form, "confirm")); | |
| 21 | if (done.ok) return flashTo(ctx, "/traces", { message: receiptWords(done.title, done.bytes) }); | |
| 22 | if (done.error === "not_found") return notFoundPage(ctx); | |
| 23 | refuseHere(ctx, refused(form, { confirm: REFUSALS[done.error] })); | |
| 24 | return asRefusal(importedTracePage(ctx, row)); | |
| 25 | } |
src/web/pages/trace_delete_form.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | /** | |
| 2 | * The red Delete on an imported session's page (#18389): a `details` (no script, no layout shift | |
| 3 | * when it opens) holding a same-origin POST form that asks for the session's title typed exactly. | |
| 4 | * The input's `pattern` is that title, so a browser keeps the button from submitting until it | |
| 5 | * matches; the server checks it again (`deleteImportedSession`) and a plain click removes nothing. | |
| 6 | */ | |
| 7 | import { html, type Html } from "../html.ts"; | |
| 8 | import { btn, field } from "../ui.ts"; | |
| 9 | ||
| 10 | /** The title as a pattern that matches only itself (the whole value, as a pattern always does). */ | |
| 11 | const literal = (s: string): string => s.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&"); | |
| 12 | ||
| 13 | export function deleteControl(base: string, title: string, shared: boolean, error?: string): Html { | |
| 14 | return html`<details class="trace-delete" id="trace-delete"${error === undefined ? null : html` open`}> | |
| 15 | <summary class="btn" data-variant="danger" data-size="sm">Delete this session</summary> | |
| 16 | <form method="post" action="${base}/delete" class="stack"> | |
| 17 | <p class="small">Deleting removes the stored file and its index rows for good, and frees the room it took in your imports. The forge keeps no other copy.${shared ? " It has a live share link: stop sharing it first, or the delete is refused." : " If you share it by a link, stop sharing first."}</p> | |
| 18 | ${field({ name: "confirm", id: "trace-delete-title", label: "Type the session's title to confirm", value: "", required: true, pattern: literal(title), autocomplete: "off", spellcheck: false, ...(error === undefined ? {} : { error }) })} | |
| 19 | <p class="small muted mono">${title}</p> | |
| 20 | <div class="form-actions">${btn("Delete this session", { variant: "danger", type: "submit" })}</div> | |
| 21 | </form> | |
| 22 | </details>`; | |
| 23 | } |
src/web/pages/trace_imported.ts +3
| @@ -17,6 +17,8 @@ import { seenTraceRow } from "../../trace/tree.ts"; | ||
| 17 | 17 | import { notFoundPage, pageHead } from "../chrome.ts"; |
| 18 | 18 | import { html } from "../html.ts"; |
| 19 | 19 | import { page } from "../layout.ts"; |
| 20 | import { refusedHere } from "../form.ts"; | |
| 21 | import { deleteControl } from "./trace_delete_form.ts"; | |
| 20 | 22 | import { behaviorsJs } from "../behaviors.ts"; |
| 21 | 23 | import { strip, TRACE_CSS, TRACE_JS, treeRows } from "./trace.ts"; |
| 22 | 24 | |
| @@ -51,6 +53,7 @@ export function importedTracePage(ctx: Ctx, row: TraceRow): Response { | ||
| 51 | 53 | <span class="muted">${shared ? "A share link is live: anyone holding it reads this session, secrets redacted." : "Not shared. A link lets anyone who holds it read this session. The forge hides the credentials it knows, but a file can hold others, so share only what you have read."}</span> |
| 52 | 54 | <button type="submit">${shared ? "Stop sharing" : "Make a share link"}</button> |
| 53 | 55 | </form>`} |
| 56 | ${shared === undefined ? null : deleteControl(base, row.title, shared, refusedHere(ctx)?.errors.confirm)} | |
| 54 | 57 | ${read.truncated ? html`<p class="small muted" id="trace-cut">The session is longer than the page reads; only its first steps are shown.</p>` : null} |
| 55 | 58 | ${total === 0 ? html`<p class="muted" id="trace-empty">This session holds no steps.</p>` : html`${strip(steps, timed)} |
| 56 | 59 | <div class="trace-tree" id="trace-tree" data-base="${base}" role="group" aria-label="Steps">${treeRows(steps, base, timed)}</div> |
test/trace-imported-delete.test.ts added +140
| @@ -0,0 +1,140 @@ | ||
| 1 | /** The red Delete on an imported session's page, and its terminal key (#18389). */ | |
| 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 3 | import { existsSync } from "node:fs"; | |
| 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 { makeShare } from "../src/trace/share.ts"; | |
| 9 | import { createToken } from "../src/core/tokens.ts"; | |
| 10 | import { createUser, type User } from "../src/core/users.ts"; | |
| 11 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 12 | import { importSession } from "../src/trace/import.ts"; | |
| 13 | import { putTraceRow } from "../src/trace/index_table.ts"; | |
| 14 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 15 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 16 | import { entry } from "../src/tui/screens/traces.ts"; | |
| 17 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | import { settleApp } from "./helpers/tui.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | const TITLE = "fix the login bug"; | |
| 24 | const rec = (o: object): string => JSON.stringify({ sessionId: "sess-w", cwd: "/w", ...o }); | |
| 25 | const SESSION = [ | |
| 26 | rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: TITLE } }), | |
| 27 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "text", text: "Done" }] } }), | |
| 28 | ].join("\n"); | |
| 29 | ||
| 30 | let dir = ""; | |
| 31 | let app: App, servers: Servers; | |
| 32 | let alice: User, bob: User; | |
| 33 | let aliceToken = "", bobToken = "", id = ""; | |
| 34 | ||
| 35 | const get = (path: string, token: string): Promise<Response> => fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${token}` } }); | |
| 36 | const post = (path: string, token: string, confirm: string, headers: Record<string, string> = {}): Promise<Response> => | |
| 37 | fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { authorization: `Bearer ${token}`, ...headers }, body: new URLSearchParams({ confirm }) }); | |
| 38 | const file = (i: string): string => join(dir, "traces", "imported", `${i}.jsonl.gz`); | |
| 39 | const listed = async (): Promise<string> => await (await get("/traces", aliceToken)).text(); | |
| 40 | ||
| 41 | beforeAll(async () => { | |
| 42 | dir = await mkdtemp(join(tmpdir(), "forge-trace-imported-delete-")); | |
| 43 | app = createApp({ dataDir: dir, port: 0 }); | |
| 44 | servers = await serve(app); | |
| 45 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 46 | if (!a.ok) throw new Error(a.error); | |
| 47 | alice = a.value; | |
| 48 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 49 | if (!b.ok) throw new Error("bob"); | |
| 50 | bob = b.value; | |
| 51 | aliceToken = createToken(app.db, alice.id, "t", "rw").token; | |
| 52 | bobToken = createToken(app.db, bob.id, "t", "rw").token; | |
| 53 | const made = await importSession(app.db, dir, alice.id, new TextEncoder().encode(SESSION)); | |
| 54 | if (!made.ok) throw new Error(made.reason); | |
| 55 | id = made.row.id; | |
| 56 | }, 30_000); | |
| 57 | ||
| 58 | afterAll(async () => { | |
| 59 | await servers.stop(); | |
| 60 | app.close(); | |
| 61 | await rm(dir, { recursive: true, force: true }); | |
| 62 | }); | |
| 63 | ||
| 64 | test("the owner's page has the control, with what is lost, and another person's page is the not-found", async () => { | |
| 65 | const page = await (await get(`/traces/${id}`, aliceToken)).text(); | |
| 66 | expect(page).toContain(`action="/traces/${id}/delete"`); | |
| 67 | expect(page).toContain("Type the session's title to confirm"); | |
| 68 | expect(page).toContain("stop sharing first"); | |
| 69 | expect(page).toContain(`pattern="${TITLE}"`); | |
| 70 | expect(page).not.toContain("<details class=\"trace-delete\" id=\"trace-delete\" open"); | |
| 71 | expect((await get(`/traces/${id}`, bobToken)).status).toBe(404); | |
| 72 | expect((await post(`/traces/${id}/delete`, bobToken, TITLE)).status).toBe(404); | |
| 73 | expect(existsSync(file(id))).toBe(true); | |
| 74 | }); | |
| 75 | ||
| 76 | test("a crew run shows no control and its delete post is the not-found", async () => { | |
| 77 | putTraceRow(app.db, { id: "run0001", kind: "run", repository: "", title: "a run", model: "", account: "", steps: 0, errors: 0, tokensIn: 0, tokensCached: 0, tokensOut: 0, costUsd: 0, outcome: "ok", started: "2026-12-01T09:00:00.000Z", ended: "2026-12-01T09:00:01.000Z" }, alice.id); | |
| 78 | expect(await (await get("/traces/run0001", aliceToken)).text()).not.toContain("/delete"); | |
| 79 | expect((await post("/traces/run0001/delete", aliceToken, "a run")).status).toBe(404); | |
| 80 | expect(app.db.query("SELECT 1 FROM trace_index WHERE id = 'run0001'").get()).not.toBeNull(); | |
| 81 | app.db.query("DELETE FROM trace_index WHERE id = 'run0001'").run(); | |
| 82 | }); | |
| 83 | ||
| 84 | test("a wrong title draws the page again with why and keeps the session; a cross-site post is a 403", async () => { | |
| 85 | const wrong = await post(`/traces/${id}/delete`, aliceToken, "fix the login"); | |
| 86 | expect(wrong.status).toBe(422); | |
| 87 | const body = await wrong.text(); | |
| 88 | expect(body).toContain("not the session's exact title"); | |
| 89 | expect(body).toContain('id="trace-delete"'); | |
| 90 | expect(body).toContain("<details class=\"trace-delete\" id=\"trace-delete\" open"); | |
| 91 | expect(existsSync(file(id))).toBe(true); | |
| 92 | expect((await post(`/traces/${id}/delete`, aliceToken, TITLE, { origin: "https://evil.example" })).status).toBe(403); | |
| 93 | expect(existsSync(file(id))).toBe(true); | |
| 94 | }); | |
| 95 | ||
| 96 | test("a live share link refuses the delete and says to stop sharing first", async () => { | |
| 97 | makeShare(app.db, id, alice.id, Date.now()); | |
| 98 | const res = await post(`/traces/${id}/delete`, aliceToken, TITLE); | |
| 99 | expect(res.status).toBe(422); | |
| 100 | expect(await res.text()).toContain("stop sharing it first"); | |
| 101 | expect(existsSync(file(id))).toBe(true); | |
| 102 | app.db.query("UPDATE trace_share SET revoked_at = ?2 WHERE run_id = ?1").run(id, new Date().toISOString()); | |
| 103 | }); | |
| 104 | ||
| 105 | test("the right title removes it, lands on /traces with a receipt, and the list drops it", async () => { | |
| 106 | expect(await listed()).toContain(TITLE); | |
| 107 | const done = await post(`/traces/${id}/delete`, aliceToken, TITLE); | |
| 108 | expect(done.status).toBe(303); | |
| 109 | expect(done.headers.get("location")).toContain("/traces"); | |
| 110 | expect(existsSync(file(id))).toBe(false); | |
| 111 | const after = await listed(); | |
| 112 | expect(after).not.toContain(`/traces/${id}`); | |
| 113 | expect((await get(`/traces/${id}`, aliceToken)).status).toBe(404); | |
| 114 | }); | |
| 115 | ||
| 116 | test("D in the terminal asks for the title, and deletes only on the exact one", async () => { | |
| 117 | const made = await importSession(app.db, dir, alice.id, new TextEncoder().encode(SESSION.replace(TITLE, "ship it"))); | |
| 118 | if (!made.ok) throw new Error(made.reason); | |
| 119 | const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice }, { terminal: headlessTerminal(140, 30), exitHooks: false }); | |
| 120 | tui.start(); | |
| 121 | await settleApp(tui); | |
| 122 | entry.run(session, tui.ctx); | |
| 123 | await settleApp(tui); | |
| 124 | const press = async (key: string): Promise<string> => { | |
| 125 | tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 126 | await settleApp(tui); | |
| 127 | return tui.screen.toText(); | |
| 128 | }; | |
| 129 | const type = async (text: string): Promise<void> => { | |
| 130 | for (const ch of text) await press(ch); | |
| 131 | }; | |
| 132 | const asked = await press("D"); | |
| 133 | expect(asked).toContain("Type its title to confirm"); | |
| 134 | await type("ship"); | |
| 135 | expect(await press("enter")).toContain("not the session's exact title"); | |
| 136 | expect(existsSync(file(made.row.id))).toBe(true); | |
| 137 | await type(" it"); | |
| 138 | expect(await press("enter")).toContain("Deleted"); | |
| 139 | expect(existsSync(file(made.row.id))).toBe(false); | |
| 140 | }); |
new above
offline