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

An issue's open question stays out of the history fold #13213

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/13176-an-issue-s-open-question-stays-out-of-th → main 13 commits fork 4 threads · 4 unresolved

  • Merged. mason/13176-an-issue-s-open-question-stays-out-of-th was merged into main as 102c186.

Review

Sign in to review this change.
20 files changed +575 −21
docs/design/areas/comments.md +1
@@ -9,3 +9,4 @@ A comment on an issue or pull, and the form that writes one. Both are a `card()`
99 - `.comment-form` — the form that writes a comment: a textarea and its `.form-actions`. On a thread (`composer()`, also the reply box on a studio change) it is plain lines under the timeline, no `card`, spaced like the home composer; the floating tell box (`tell_here.ts`) passes `boxed` and so adds `card`. A review reply (`reviewRows()`) and the studio box (`studioApp()`) write their own `card comment-form`. Written by `composer()` and `editForm()` in `src/web/pages/thread.ts`, `reviewRows()` in `src/web/diff-view.ts` (a reply in a review thread) and `studioApp()` in `src/web/studio/app.ts` (the "Tell the crew" box); styled in `src/web/style/components.ts`, with its narrow-screen action line and its review-thread margin in `src/web/style/content.ts`.
1010 - `.tl-earlier` — the line above a long thread's newest items, `Show N earlier items`, a plain link to `?all=1`. Written by `conversation()` in `src/web/pages/thread.ts`; styled in `src/web/style/components.ts` beside `.tl-item`, indented to the timeline's item column.
1111 - `.tl-fold` — a plain `<details>` (id `history`) holding every timeline item before the newest comment, its summary the counts (`49 earlier comments · 3 events`). Written by `conversation()`; `client.ts` opens it when the URL hash is a `#c-…` inside it.
12 - Question row — under a comment that is an open or settled question: one `p.muted.small` saying `Question, open` or `Question, settled`, and a link-variant small `.btn` (`Settle` / `Ask again`) in a `form.inline`. Written by `threadComment()` in `src/web/pages/thread.ts`; no class of its own. An ordinary comment gets none: "Ask as a question" is a checkbox in the composer.
docs/design/attention-budget.json +4 −3
@@ -49,15 +49,16 @@
4949 },
5050 "issue": {
5151 "390": {
52 "words": 72,
52 "words": 76,
5353 "blocks": 19,
5454 "colours": 2
5555 },
5656 "1280": {
57 "words": 72,
57 "words": 76,
5858 "blocks": 19,
5959 "colours": 2
60 }
60 },
61 "note": "76 words: the composer offers \"Ask as a question\" (four words) on an issue, the one control that marks a comment as a standing question (#13176)."
6162 },
6263 "issues list": {
6364 "390": {
docs/features/README.md +1
@@ -23,6 +23,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
2323 - [/docs](docs-link.md)
2424 - [Engine shape](engine-shape.md)
2525 - [Feed fold](feed-fold.md)
26 - [Questions on an issue](question.md)
2627 - [A feed post has a permalink](feed-permalink.md)
2728 - [Feed likes: the ledger](feed-like-ledger.md)
2829 - [Forge packs: a premade forge to deploy (`/packs`)](packs.md)
docs/features/question.md added +20
@@ -0,0 +1,20 @@
1 # Questions on an issue
2
3 A comment on an issue can be a question. An open question is never folded out of a long thread: it stays on the
4 page, in view, until someone settles it. Pulls have no questions; a review asking for changes is their standing
5 request.
6
7 Who may: the comment's author, or anyone who writes in the repository. Mirrors are read-only here.
8
9 **Web:** tick "Ask as a question" beside the Comment button when posting. A question reads "Question, open" under
10 its comment with a **Settle** button; a settled one reads "Question, settled" with **Ask again**. An ordinary comment
11 has no control, so a long thread carries none on its rows. To mark an existing comment, use the API.
12
13 **API:** `POST /api/v1/repos/:owner/:name/issues/:number/comments/:id/question` with `{ "state": "open" | "settled" | "none" }`
14 (`none` takes the mark off). Needs a `rw` token: 401 without one, or for someone who may not change that comment;
15 400 for any other state; 404 for a comment that is not on that issue. The answer is the comment, with `question`.
16
17 **Terminal:** on an issue, `Q` opens the composer as "Question" and posts the comment as an open question (if the
18 mark is refused the toast says so); `z` settles the newest open question, or says "no open question".
19
20 Pinned by `test/thread-window.test.ts` (the fold, the page) and `test/question-api.test.ts` (the API, the terminal).
src/actions/issues.ts +32 −2
@@ -39,6 +39,7 @@ import {
3939 labelsFor,
4040 listComments,
4141 setAssignee,
42 setCommentQuestion,
4243 setIssueLabels as writeLabels,
4344 setIssueState as writeState,
4445 updateIssueText,
@@ -47,6 +48,7 @@ import {
4748 type Issue,
4849 type IssueState,
4950 type Label,
51 type QuestionState,
5052 type BodyError,
5153 type TitleError,
5254 standsForPerson,
@@ -103,7 +105,8 @@ export function openIssue(
103105 const user = requireParticipant(app, actor, repo);
104106 if (!user.ok) return user;
105107 if (isMirror(app, repo)) return err("mirrored");
106 // The owner's switch (#11604): a paused planner opens nothing, and says so; everyone else is unaffected.
108 // The owner's switch (#11604): a paused planner opens nothing, and says so; everyone else is
109 // unaffected.
107110 if (
108111 user.value.kind === "agent" &&
109112 crewRole(app.db, repo.id, user.value.id) === "planner" &&
@@ -396,6 +399,30 @@ export function addComment(
396399 return added;
397400 }
398401
402 /**
403 * Mark a comment on an issue as a question, settle it, or take the mark off
404 * (`null`). The comment's author or a person who writes here may; an open
405 * question is never folded out of a long thread. Issues only: a pull already
406 * has its own standing request, the review.
407 */
408 export function markQuestion(
409 app: App,
410 actor: User | undefined,
411 repo: Repo,
412 issue: Issue,
413 commentId: string,
414 state: QuestionState | null,
415 ): Result<Comment, "not_found" | "unauthorized" | MirrorError> {
416 const user = requireParticipant(app, actor, repo);
417 if (!user.ok) return user;
418 if (issue.repoId !== repo.id || issue.kind !== "issue") return err("not_found");
419 if (isMirror(app, repo)) return err("mirrored");
420 const comment = listComments(app.db, issue.id, { kind: "comment" }).find((c) => c.id === commentId);
421 if (comment === undefined) return err("not_found");
422 if (comment.authorId !== user.value.id && !canWrite(app.db, repo, user.value)) return err("unauthorized");
423 return setCommentQuestion(app.db, issue.id, commentId, state);
424 }
425
399426 /**
400427 * Close or reopen an issue or a pull. The author or a repo writer may; the
401428 * change is a CAS, so a no-op transition records nothing and returns the
@@ -712,7 +739,10 @@ export function plannerCloseRefusal(
712739 : refused;
713740 }
714741
715 /** What a close can be refused for beyond access: a merged pull, a bad reason or note, a bug with no why. */
742 /**
743 * What a close can be refused for beyond access: a merged pull, a bad reason or note, a bug with no
744 * why.
745 */
716746 export type CloseError =
717747 | "already_merged"
718748 | "invalid_reason"
src/contract/openapi/routes/index.ts +1
@@ -362,6 +362,7 @@ export { route as postApiV1ReposOwnerNameHooksIdPing } from "./postApiV1ReposOwn
362362 export { route as postApiV1ReposOwnerNameHooksIdResume } from "./postApiV1ReposOwnerNameHooksIdResume.ts";
363363 export { route as postApiV1ReposOwnerNameIssues } from "./postApiV1ReposOwnerNameIssues.ts";
364364 export { route as postApiV1ReposOwnerNameIssuesNumberComments } from "./postApiV1ReposOwnerNameIssuesNumberComments.ts";
365 export { route as postApiV1ReposOwnerNameIssuesNumberCommentsIdQuestion } from "./postApiV1ReposOwnerNameIssuesNumberCommentsIdQuestion.ts";
365366 export { route as postApiV1ReposOwnerNameIssuesNumberDependencies } from "./postApiV1ReposOwnerNameIssuesNumberDependencies.ts";
366367 export { route as postApiV1ReposOwnerNameIssuesNumberDependenciesBlockerConfirm } from "./postApiV1ReposOwnerNameIssuesNumberDependenciesBlockerConfirm.ts";
367368 export { route as postApiV1ReposOwnerNameIssuesNumberEstimates } from "./postApiV1ReposOwnerNameIssuesNumberEstimates.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameIssuesNumberCommentsIdQuestion.ts added +10
@@ -0,0 +1,10 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/issues/{number}/comments/{id}/question`,
6 summary: "Mark an issue comment as a question, settle it, or take the mark off: state is open, settled or none; an open question is never folded out of a long thread",
7 auth: true,
8 role: "member",
9 body: { state: "string" },
10 };
src/core/issues.ts +45 −4
@@ -102,7 +102,9 @@ const SELECT = `
102102 FROM issue JOIN user ON user.id = issue.author_id
103103 LEFT JOIN user AS assignee ON assignee.id = issue.assignee_id`;
104104
105 /** `SELECT` without the body: a plan reads titles and states, and a body is most of a row's bytes. */
105 /**
106 * `SELECT` without the body: a plan reads titles and states, and a body is most of a row's bytes.
107 */
106108 const SELECT_LEAN = SELECT.replace(
107109 "issue.*,",
108110 `issue.id, issue.repo_id, issue.number, issue.kind, issue.title, '' AS body, issue.author_id,
@@ -473,7 +475,9 @@ export interface ListIssuesOptions {
473475 * forgets shows nothing sealed.
474476 */
475477 sealed?: boolean;
476 /** Include the sealed issues this user filed (`sealed.ts`): a reporter follows their own report. */
478 /**
479 * Include the sealed issues this user filed (`sealed.ts`): a reporter follows their own report.
480 */
477481 sealedBy?: string;
478482 }
479483
@@ -593,6 +597,34 @@ export interface Comment {
593597 * not heard, and the word is news to the next run.
594598 */
595599 readonly heardIn: string | null;
600 /**
601 * A comment can be a question: "open" until someone settles it, "settled"
602 * after. Null for an ordinary comment. An open question is never folded
603 * out of a long thread (`conversation()`, web/pages/thread.ts).
604 */
605 readonly question: QuestionState | null;
606 }
607
608 export type QuestionState = "open" | "settled";
609
610 export function parseQuestion(value: unknown): QuestionState | null | undefined {
611 if (value === "open" || value === "settled") return value;
612 if (value === "none" || value === null || value === "") return null;
613 return undefined;
614 }
615
616 /** Mark a comment as a question, settle it, or make it an ordinary comment again (null). */
617 export function setCommentQuestion(
618 db: Database,
619 issueId: string,
620 commentId: string,
621 state: QuestionState | null,
622 ): Result<Comment, "not_found"> {
623 const done = db
624 .query("UPDATE comment SET question = ?1 WHERE id = ?2 AND issue_id = ?3 AND kind = 'comment'")
625 .run(state, commentId, issueId);
626 if (done.changes === 0) return err("not_found");
627 return ok(getComment(db, commentId)!);
596628 }
597629
598630 /** Record that run `runId` heard comment `commentId` as it worked. */
@@ -674,6 +706,7 @@ function getComment(db: Database, commentId: string): Comment | undefined {
674706 created_at: string;
675707 origin_author: string | null;
676708 heard_ok: string | null;
709 question: string | null;
677710 },
678711 [string]
679712 >(
@@ -693,6 +726,7 @@ function getComment(db: Database, commentId: string): Comment | undefined {
693726 createdAt: row.created_at,
694727 originAuthor: row.origin_author,
695728 heardIn: row.heard_ok,
729 question: row.question === "open" || row.question === "settled" ? row.question : null,
696730 };
697731 }
698732
@@ -714,7 +748,9 @@ export interface ListCommentsOptions {
714748 limit?: number;
715749 }
716750
717 /** How many of a thread's newest comments an issue read embeds, on the API and in the MCP (#6198). */
751 /**
752 * How many of a thread's newest comments an issue read embeds, on the API and in the MCP (#6198).
753 */
718754 export const EMBEDDED_COMMENTS = 50;
719755
720756 /** How many timeline items a thread page shows before it folds the earlier ones behind `?all=1`. */
@@ -763,6 +799,7 @@ export function listComments(
763799 created_at: string;
764800 origin_author: string | null;
765801 heard_ok: string | null;
802 question: string | null;
766803 },
767804 string[]
768805 >(
@@ -783,6 +820,7 @@ export function listComments(
783820 createdAt: row.created_at,
784821 originAuthor: row.origin_author,
785822 heardIn: row.heard_ok,
823 question: row.question === "open" || row.question === "settled" ? row.question : null,
786824 }));
787825 }
788826
@@ -911,7 +949,10 @@ export function openLabelCounts(
911949 return new Map([...openLabelUse(db, repoId)].map(([label, use]) => [label, use.all]));
912950 }
913951
914 /** What carries a label, open: `issues` and `pulls` as the lists narrowed to it count them, and `all`. */
952 /**
953 * What carries a label, open: `issues` and `pulls` as the lists narrowed to it count them, and
954 * `all`.
955 */
915956 export interface LabelUse {
916957 /** Open issues the issues list shows under the label: not sealed, not the standing direction. */
917958 readonly issues: number;
src/core/migration-pins/20261115110000-comment-question.pin added +1
@@ -0,0 +1,1 @@
1 a1b4e4e669af5268ef6556c55303a890eaa8783891267cf86ce1ae09fd7ce8c7
src/core/migrations/20261115110000-comment-question.ts added +6
@@ -0,0 +1,6 @@
1 // A comment can be a question (#13176): null for an ordinary comment, 'open'
2 // until it is settled, then 'settled'. An open one stays out of the history
3 // fold. Additive; undone by dropping the column.
4 export default `
5 ALTER TABLE comment ADD COLUMN question TEXT;
6 `;
src/http/api/issues.ts +21
@@ -5,6 +5,8 @@
55 * (#7450); the rules live in `actions/issues.ts` and its neighbours.
66 */
77
8 import { markQuestion } from "../../actions/issues.ts";
9 import { parseQuestion } from "../../core/issues.ts";
810 import { mayReadRuns } from "../../actions/runs.ts";
911 import { costField, issueCostFor } from "../../core/issue_cost.ts";
1012 import { holds, weakEtag } from "../etag.ts";
@@ -584,4 +586,23 @@ export function issueRoutes(router: Router<Handler>): void {
584586 return json(added.value, 201);
585587 },
586588 );
589
590 // Settle a question, ask it again, or take the mark off:
591 // `{ state: "open" | "settled" | "none" }`.
592 router.add(

No test for this route: add one covering 401 without a token, 400 on a bad state, 403/404 for a non-author non-writer, and success.

593 "POST",
594 "/api/v1/repos/:owner/:name/issues/:number/comments/:id/question",
595 async (ctx) => {
596 const denied = requireScope(ctx, "rw");
597 if (denied) return denied;
598 const found = loadIssue(ctx);
599 if ("error" in found) return found.error;
600 const input = await body(ctx.request);
601 const state = parseQuestion(input.state);
602 if (state === undefined) return apiError("invalid", 400, 'state is "open", "settled" or "none"');
603 const marked = markQuestion(ctx.app, ctx.auth.user, found.repo, found.issue, ctx.params.id ?? "", state);
604 if (!marked.ok) return originAware(marked.error);
605 return json(marked.value);
606 },
607 );
587608 }
src/http/server.ts +6
@@ -255,6 +255,7 @@ import { commitPage, commitsPage } from "../web/pages/commits.ts";
255255 import { eventsList } from "../web/pages/events.ts";
256256 import {
257257 issueCommentSubmit,
258 issueQuestionSubmit,
258259 issuePrivateSubmit,
259260 issueSealSubmit,
260261 issueThreadFragment,
@@ -1349,6 +1350,11 @@ export function buildRouter(): Router<Handler> {
13491350 "/:owner/:name/issues/:number/comments",
13501351 issueCommentSubmit,
13511352 );
1353 router.add(
1354 "POST",
1355 "/:owner/:name/issues/:number/comments/:id/question",
1356 issueQuestionSubmit,
1357 );
13521358 router.add("POST", "/:owner/:name/issues/:number/seal", issueSealSubmit);
13531359 router.add("POST", "/:owner/:name/issues/:number/private", issuePrivateSubmit);
13541360 // Close/reopen and labels are their own verbs, not riders on a comment.
src/tui/screens/issue.ts +40 −2
@@ -50,6 +50,7 @@ import { alreadyDone } from "../../core/done_on_main.ts";
5050 import { hasPicture } from "../../core/note_pictures.ts";
5151 import { isMirror } from "../../origins/write-through.ts";
5252 import { getIssue, type Issue, type Label } from "../../core/issues.ts";
53 import { markQuestion } from "../../actions/issues.ts";
5354 import type { Repo } from "../../core/repos.ts";
5455 import type { IssueDetail, RepoSource } from "../../view/source.ts";
5556 import type { Ctx, Screen } from "../app/app.ts";
@@ -289,26 +290,51 @@ export function issueScreen(
289290 kind: "comment" as const,
290291 actor: who(comment.authorName, comment.originAuthor),
291292 at: comment.createdAt,
292 body: comment.body,
293 body: comment.question === "open" ? `${comment.body}\n\n_Open question_` : comment.body,
293294 })),
294295 ];
295296
296297 // The `…Through` twins: identical on a native repo, and on a mirror they
297298 // write to the origin first and reflect what came back.
299 /** Whether the comment in the composer is posted as an open question (`Q`). */
300 let asQuestion = false;
301 /** `z`: settle the newest open question on this issue. */
302 const settle = (): void => {
303 const at = row();
304 if (at?.issue === undefined || detail === undefined) return;
305 const open = detail.comments.filter((c) => c.question === "open").at(-1);
306 if (open === undefined) {
307 ctx.toast("no open question", "attn");
308 return;
309 }
310 const marked = markQuestion(f.app, f.user, at.repo, at.issue, open.id, "settled");
311 if (!marked.ok) {
312 ctx.toast(errorText(marked.error), "danger");
313 return;
314 }
315 runAsync(ctx, async () => {
316 await reload();
317 ctx.toast("question settled", "success");
318 });
319 };
320
298321 const submit = (): void => {
299322 const at = row();
300323 if (at?.issue === undefined) return;
301324 const { repo: target, issue } = at;
302325 const body = composer.value;
326 const asking = asQuestion;
303327 runAsync(ctx, async () => {
304328 const added = await addCommentThrough(f.app, f.user, target, issue, body);
305329 if (!added.ok) {
306330 ctx.toast(errorText(added.error), "danger");
307331 return;
308332 }
333 const marked = asking ? markQuestion(f.app, f.user, target, issue, added.value.id, "open") : undefined;
outdated

The result of markQuestion is dropped: if it refuses, the comment is posted as an ordinary one and the toast says 'comment posted'. Check the result and toast the failure. Also add a tui test for Q and z; box 1 asks for the terminal door.

309334 composer.close();
310335 await reload();
311 ctx.toast("comment posted", "success");
336 if (marked !== undefined && !marked.ok) ctx.toast(`comment posted, not as a question: ${errorText(marked.error)}`, "danger");
337 else ctx.toast(asking ? "question posted" : "comment posted", "success");
312338 });
313339 };
314340
@@ -574,6 +600,8 @@ export function issueScreen(
574600 ? [binding(["p"], "private repo")]
575601 : []),
576602 binding(["f"], "flow first"),
603 binding(["Q"], "ask a question"),
604 binding(["z"], "settle question"),
577605 ]
578606 : [
579607 ...(mayEdit() ? [binding(["e"], "edit")] : []),
@@ -780,9 +808,19 @@ export function issueScreen(
780808 return true;
781809 }
782810 if (e.key === "c" && mayWrite()) {
811 asQuestion = false;
783812 composer.start("Comment");
784813 return true;
785814 }
815 if (e.key === "Q" && mayWrite()) {
816 asQuestion = true;
817 composer.start("Question");
818 return true;
819 }
820 if (e.key === "z" && mayWrite()) {
821 settle();
822 return true;
823 }
786824 if (e.key === "e" && mayEdit()) {
787825 startEdit();
788826 return true;
src/view/local.ts +1
@@ -301,6 +301,7 @@ export function localSource(
301301 originUrl: null,
302302 body: c.body,
303303 createdAt: c.createdAt,
304 question: c.question,
304305 }));
305306
306307 let pull: PullFacts | null = null;
src/view/source.ts +2
@@ -159,6 +159,8 @@ export interface CommentView {
159159 readonly originUrl: string | null;
160160 readonly body: string;
161161 readonly createdAt: string;
162 /** Open until settled; null for an ordinary comment (`Comment.question`). Local sources only. */
163 readonly question?: "open" | "settled" | null;
162164 }
163165
164166 /** One verdict on a pull, as either side reports it. */
src/web/pages/issues.ts +33 −1
@@ -8,10 +8,11 @@
88 import { CEILING_REFUSAL, PAUSE_REFUSAL } from "../../core/planner_pause.ts";
99 import {
1010 addCommentThrough,
11 markQuestion,
1112 openIssueThrough,
1213 setIssueSealed,
1314 } from "../../actions/issues.ts";
14 import type { Issue } from "../../core/issues.ts";
15 import { parseQuestion, type Issue } from "../../core/issues.ts";
1516 import { canRead, getRepo, listReposWritableTo, type Repo } from "../../core/repos.ts";
1617 import { reportsClosed } from "../../core/reports.ts";
1718 import { privateRepoForSealed } from "../../actions/repos.ts";
@@ -379,6 +380,15 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
379380 tone: "danger",
380381 message: originError(added.error) ?? COMMENT_NOT_POSTED,
381382 });
383 // "Ask as a question": the comment is posted either way; a refusal to mark it is said.
384 if (field(form, "question") === "open") {
385 const marked = markQuestion(ctx.app, ctx.auth.user, found.repo, found.issue, added.value.id, "open");
386 if (!marked.ok)
387 return flashTo(ctx, dest, {
388 tone: "danger",
389 message: "Comment posted, but it could not be marked as a question.",
390 });
391 }
382392 return back === undefined
383393 ? flashTo(ctx, `${dest}#conversation`, { message: "Comment posted." })
384394 : flashTo(ctx, back.to, {
@@ -386,5 +396,27 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
386396 });
387397 }
388398
399 // POST /:owner/:name/issues/:number/comments/:id/question — settle a question or ask it again
400 export async function issueQuestionSubmit(ctx: Ctx): Promise<Response> {
401 const found = threadContext(ctx, "issue");
402 if (found instanceof Response) return found;
403 if (!ctx.auth.user) return signInFirst(ctx);
404 const form = await readForm(ctx, "rw");
405 if (form instanceof Response) return form;
406 const dest = `${repoBase(found.repo)}/issues/${found.issue.number}`;
407 const state = parseQuestion(field(form, "state"));
408 if (state === undefined)
409 return flashTo(ctx, dest, { tone: "danger", message: "A question is open, settled or not a question." });
410 const marked = markQuestion(ctx.app, ctx.auth.user, found.repo, found.issue, ctx.params.id ?? "", state);
411 if (!marked.ok)
412 return flashTo(ctx, dest, {
413 tone: "danger",
414 message: originError(marked.error) ?? "Only the comment's author or someone who writes here can change a question.",
415 });
416 return flashTo(ctx, `${dest}#c-${marked.value.id}`, {
417 message: state === "settled" ? "Question settled." : state === "open" ? "Question open." : "Question mark removed.",
418 });
419 }
420
389421 export { parseNumber };
390422 export type { Issue };
src/web/pages/thread.ts +45 −3
@@ -36,7 +36,9 @@ import {
3636 type CloseReason,
3737 type Issue,
3838 type Label,
39 type QuestionState,
3940 } from "../../core/issues.ts";
41 import { isMirror } from "../../origins/write-through.ts";
4042 import { editIssue, type Closing } from "../../actions/issues.ts";
4143 import { putFlowFirst } from "../../actions/flow_first.ts";
4244 import {
@@ -153,7 +155,10 @@ export interface Entry {
153155 * same).
154156 */
155157 comment?: true;
156 /** A question still waiting for its answer (a standing request for changes): never folded. */
158 /**
159 * A standing request that stays out of the history fold: an unsettled
160 * question on an issue (and, on a pull, a review asking for changes).
161 */
157162 open?: true;
158163 }
159164
@@ -377,13 +382,26 @@ export function conversation(
377382 issue.authorName,
378383 ...comments.map((c) => c.authorName),
379384 ]);
385 // Who may mark or settle a question here: the comment's author or a person
386 // who writes, on an issue that is ours (`markQuestion`, actions/issues.ts).
387 const viewer = ctx.auth.user;
388 const mayAsk = (authorId: string): boolean =>
389 issue.kind === "issue" &&
390 viewer !== undefined &&
391 !isMirror(ctx.app, repo) &&
392 (viewer.id === authorId || canWrite(ctx.app.db, repo, viewer));
380393 const entries: Entry[] = comments.map((c) => ({
381394 at: c.createdAt,
382395 comment: true as const,
396 ...(c.question === "open" ? { open: true as const } : {}),
383397 node: threadComment(c.id, c.authorName, c.createdAt, c.body, {
384398 originAuthor: c.originAuthor,
385399 originKind: glyph,
386400 mark: marks.get(c.authorName),
401 question: {
402 state: c.question,
403 ...(mayAsk(c.authorId) ? { action: `${repoBase(repo)}/issues/${issue.number}/comments/${c.id}/question` } : {}),
404 },
387405 }),
388406 }));
389407 entries.push(...stateEvents(ctx, repo, issue));
@@ -407,7 +425,11 @@ export function conversation(
407425 }
408426 }
409427 }
410 const shown = hidden === 0 ? entries : entries.slice(hidden);
428 // An unsettled question is a standing request: it stays on the page however
429 // old, in its place, ahead of the window.
430 const kept = hidden === 0 ? [] : entries.slice(0, hidden).filter((e) => e.open === true);
431 hidden -= kept.length;
432 const shown = hidden + kept.length === 0 ? entries : [...kept, ...entries.slice(hidden + kept.length)];
411433 const more = new URLSearchParams(ctx.url.searchParams);
412434 more.set("all", "1");
413435 const earlier =
@@ -487,8 +509,21 @@ export function threadComment(
487509 originAuthor?: string | null;
488510 originKind?: Glyph;
489511 mark?: Mark | undefined;
512 question?: { state: QuestionState | null; action?: string };
490513 } = {},
491514 ): Html {
515 // Only a question that is open or settled carries a control: an ordinary comment is not given a
516 // form (a long thread would be chrome on every row). "Ask as a question" is in the composer.
517 const q = origin.question;
outdated

Dead branch: : "open" repeats the first arm of the ternary; reduce to q?.state === "settled" ? "open" : "open", i.e. next is settled only when open. Simplify.

518 const flag =
519 q?.state == null
outdated

Principles 3, 6, 7 and the component rule: tl-question is a hand-rolled class with no CSS and no entry in docs/design/areas. Use a named component (a muted row with a plain link-button) and document the class if you add one. A form per comment also bloats every long thread.

520 ? null
521 : html`<p class="muted small">${q.state === "open" ? "Question, open" : "Question, settled"}${q.action === undefined
522 ? null
523 : html` <form method="post" action="${q.action}" class="inline">
524 <input type="hidden" name="state" value="${q.state === "open" ? "settled" : "open"}" />
525 <button class="btn" data-variant="link" data-size="sm" type="submit">${q.state === "open" ? "Settle" : "Ask again"}</button>
526 </form>`}</p>`;
492527 return html`<div class="tl-item" id="c-${id}" data-kind="comment" data-comment-id="${id}">
493528 <span class="tl-dot">${icon("comment")}</span>${commentCard({
494529 id,
@@ -503,7 +538,7 @@ export function threadComment(
503538 ...(origin.originKind === undefined
504539 ? {}
505540 : { originKind: origin.originKind }),
506 })}
541 })}${flag}
507542 </div>`;
508543 }
509544
@@ -579,6 +614,8 @@ export interface ComposerOptions {
579614 * sits over the page and needs its own ground. A thread's box is plain lines. */
580615 boxed?: boolean;
581616 tell?: { from: string | null; rows?: number; page?: string; pull?: number; text?: string; ask?: boolean };
617 /** Offer "Ask as a question" (issues only): the comment posts as an open question. */
618 question?: boolean;
582619 }
583620
584621 /** The comment box. Close and reopen are their own form, not an `intent`
@@ -696,6 +733,11 @@ export function composer(ctx: Ctx, o: ComposerOptions): Html {
696733 <code>&gt; quote</code>.`}</span
697734 >
698735 <span class="spacer"></span>
736 ${o.question && !tell
737 ? html`<label class="muted small"
738 ><input type="checkbox" name="question" value="open" /> Ask as a question</label
739 >`
740 : null}
699741 ${reasons} ${closeButton}
700742 ${tell
701743 ? btn("Tell the crew", { variant: "primary", icon: "bot" })
src/web/studio/tell.ts +6 −3
@@ -376,7 +376,9 @@ async function tellRuns(
376376 })}${costBlock(cost, base)}`;
377377 }
378378
379 /** What the issue and its closing pulls cost, as `dl` rows; nothing when there is no cost to show. */
379 /**
380 * What the issue and its closing pulls cost, as `dl` rows; nothing when there is no cost to show.
381 */
380382 function costBlock(cost: IssueCost | null, base: string): Html | null {
381383 if (cost === null) return null;
382384 return html`<dl class="status-rows" data-issue-cost>${costRows(cost).map(
@@ -404,8 +406,8 @@ async function tellClosingPull(
404406 }
405407
406408 /**
407 * GET /:owner/:name/issues/:number, for every repository and every viewer. Same `threadContext` at both, so a reader who
408 * may not see it gets the forge's not-found at either.
409 * GET /:owner/:name/issues/:number, for every repository and every viewer. Same `threadContext` at
410 * both, so a reader who may not see it gets the forge's not-found at either.
409411 */
410412 export async function tellPage(ctx: Ctx): Promise<Response> {
411413 const found = threadContext(ctx, "issue");
@@ -589,6 +591,7 @@ async function studioTell(
589591 closeLabel: "Close issue",
590592 crewNote: threadNote(ctx.app.db, repo, issue),
591593 reasons: true,
594 question: true,
592595 })}
593596 </div>
594597 <aside>
test/question-api.test.ts added +221
@@ -0,0 +1,221 @@
1 /**
2 * POST …/issues/:n/comments/:id/question: the API door for marking, settling and unmarking a
3 * question; and the terminal's issue screen: Q posts the comment as an open question, z settles the
4 * newest.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { addComment, markQuestion, openIssue } from "../src/actions/issues.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { listComments, type Issue } from "../src/core/issues.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { getRepoById } from "../src/core/repos.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import { issueScreen } from "../src/tui/screens/issue.ts";
21 import { local } from "../src/tui/screens/where.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { settleApp } from "./helpers/tui.ts";
25
26 quietLogs();
27
28 let dataDir = "";
29 let app: App;
30 let servers: Servers;
31 let alice: User;
32 let bob: User;
33 let repo: Repo;
34 let issue: Issue;
35 let commentId = "";
36 let aliceToken = "";
37 let bobToken = "";
38 let carolToken = "";
39 const cells = process.env["FORGE_CELLS"];
40
41 const user = async (username: string, first: boolean): Promise<User> => {
42 const made = await createUser(app.db, {
43 origin: "seed",
44 trusted: true,
45 username,
46 email: `${username}@forge.local`,
47 password: "a-good-passphrase",
48 adminIfFirst: first,
49 });
50 if (!made.ok) throw new Error(String(made.error));
51 return made.value;
52 };
53
54 beforeAll(async () => {
55 process.env["FORGE_CELLS"] = "off";
56 dataDir = await mkdtemp(join(tmpdir(), "forge-question-api-"));
57 app = createApp({ dataDir, port: 0 });
58 servers = await serve(app);
59 alice = await user("alice", true);
60 bob = await user("bob", false);
61 const carol = await user("carol", false);
62 aliceToken = createToken(app.db, alice.id, "t", "rw").token;
63 bobToken = createToken(app.db, bob.id, "t", "rw").token;
64 carolToken = createToken(app.db, carol.id, "t", "rw").token;
65 const r = await createRepo(app, alice, { name: "r", visibility: "public" });
66 if (!r.ok) throw new Error(String(r.error));
67 repo = r.value;
68 const opened = openIssue(app, alice, repo, { title: "Asked", body: "x" });
69 if (!opened.ok) throw new Error(String(opened.error));
70 issue = opened.value;
71 // bob's comment: alice (a writer) and bob (its author) may change it; carol may not.
72 const said = addComment(app, bob, repo, issue, "which database?");
73 if (!said.ok) throw new Error(String(said.error));
74 commentId = said.value.id;
75 });
76 afterAll(async () => {
77 await servers.stop();
78 app.close();
79 if (cells === undefined) delete process.env["FORGE_CELLS"];
80 else process.env["FORGE_CELLS"] = cells;
81 await rm(dataDir, { recursive: true, force: true });
82 });
83
84 const post = (token: string | undefined, state: unknown, id = commentId): Promise<Response> =>
85 fetch(`${servers.url}/api/v1/repos/alice/r/issues/${issue.number}/comments/${id}/question`, {
86 method: "POST",
87 headers: { "content-type": "application/json", ...(token === undefined ? {} : { authorization: `Bearer ${token}` }) },
88 body: JSON.stringify({ state }),
89 });
90 const stored = () => listComments(app.db, issue.id, { kind: "comment" }).find((c) => c.id === commentId)!.question;
91
92 test("no token is refused with 401 and changes nothing", async () => {
93 expect((await post(undefined, "open")).status).toBe(401);
94 expect(stored()).toBeNull();
95 });
96
97 test("a state that is not open, settled or none is a 400", async () => {
98 const res = await post(bobToken, "later");
99 expect(res.status).toBe(400);
100 expect(stored()).toBeNull();
101 });
102
103 test("a person who neither wrote the comment nor writes here is refused, as every action's refusal is: 401", async () => {
104 expect((await post(carolToken, "open")).status).toBe(401);
105 expect(stored()).toBeNull();
106 });
107
108 test("an unknown comment is a 404", async () => {
109 expect((await post(aliceToken, "open", "nope")).status).toBe(404);
110 });
111
112 test("the author opens it, a writer settles it, and none takes the mark off", async () => {
113 const opened = await post(bobToken, "open");
114 expect(opened.status).toBe(200);
115 expect(((await opened.json()) as { question: string }).question).toBe("open");
116 expect(stored()).toBe("open");
117 expect((await post(aliceToken, "settled")).status).toBe(200);
118 expect(stored()).toBe("settled");
119 expect((await post(bobToken, "none")).status).toBe(200);
120 expect(stored()).toBeNull();
121 });
122
123
124 describe("the terminal's issue screen asks and settles questions", () => {
125 let dataDir = "";
126 let app: App;
127 let alice: User;
128 let bob: User;
129 let repo: Repo;
130 const opened: { stop(): void }[] = [];
131
132 const open = async (user: User, issue: Issue) => {
133 const terminal = headlessTerminal(140, 40);
134 const { app: tui, session } = createForgeApp(
135 app,
136 { sshUsername: "t", remoteAddress: "127.0.0.1", user },
137 { terminal, exitHooks: false },
138 );
139 tui.start();
140 opened.push(tui);
141 await settleApp(tui);
142 tui.push(issueScreen(session, tui.ctx, local(session, getRepoById(app.db, repo.id)!), issue.number));
143 await settleApp(tui);
144 const key = async (k: string, ctrl = false) => {
145 tui.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
146 await settleApp(tui);
147 };
148 const type = async (text: string) => {
149 for (const ch of text) await key(ch);
150 };
151 return { key, type, text: () => tui.screen.toText() };
152 };
153
154 beforeAll(async () => {
155 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-question-"));
156 app = createApp({ dataDir, port: 0 });
157 for (const username of ["alice", "bob"]) {
158 const made = await createUser(app.db, {
159 origin: "seed",
160 trusted: true,
161 username,
162 email: `${username}@forge.local`,
163 password: "a-good-passphrase",
164 adminIfFirst: username === "alice",
165 });
166 if (!made.ok) throw new Error(made.error);
167 if (username === "alice") alice = made.value;
168 else bob = made.value;
169 }
170 const r = await createRepo(app, alice, { name: "garden", visibility: "public" });
171 if (!r.ok) throw new Error(String(r.error));
172 repo = r.value;
173 }, 30_000);
174
175 afterAll(async () => {
176 for (const tui of opened) tui.stop();
177 await new Promise((r) => setTimeout(r, 100)); // real-timer: lets the stopped TUI sockets drain before the app closes
178 app.close();
179 await rm(dataDir, { recursive: true, force: true });
180 });
181
182 const newIssue = (title: string): Issue => {
183 const o = openIssue(app, alice, getRepoById(app.db, repo.id)!, { title, body: "" });
184 if (!o.ok) throw new Error(String(o.error));
185 return o.value;
186 };
187 const comments = (issue: Issue) => listComments(app.db, issue.id, { kind: "comment" });
188
189 test("Q opens a Question box and the comment is stored as an open question", async () => {
190 const issue = newIssue("ask me");
191 const t = await open(alice, issue);
192 await t.key("Q");
193 expect(t.text()).toContain("Question");
194 await t.type("which db");
195 await t.key("d", true);
196 const got = comments(issue);
197 expect(got.length).toBe(1);
198 expect(got[0]!.body).toBe("which db");
199 expect(got[0]!.question).toBe("open");
200 });
201
202 test("z settles the open question, and says so when there is none", async () => {
203 const issue = newIssue("settle me");
204 const t = await open(alice, issue);
205 await t.key("z");
206 expect(t.text()).toContain("no open question");
207 const said = addComment(app, alice, getRepoById(app.db, repo.id)!, issue, "ok?");
208 if (!said.ok) throw new Error(String(said.error));
209 markQuestion(app, alice, getRepoById(app.db, repo.id)!, issue, said.value.id, "open");
210 const again = await open(alice, issue);
211 await again.key("z");
212 expect(comments(issue)[0]!.question).toBe("settled");
213 });
214
215 test("a reader has neither key", async () => {
216 const issue = newIssue("hands off");
217 const t = await open(bob, issue);
218 await t.key("Q");
219 expect(t.text()).not.toContain("Question");
220 });
221 });
test/thread-window.test.ts +79 −3
@@ -1,11 +1,11 @@
11 /** A long thread shows its opening post and newest 50 items; `?all=1` shows everything (#6124). */
22 import { afterAll, beforeAll, expect, test } from "bun:test";
33 import { snappyFixture, type SnappyFixture } from "../bench/snappy.ts";
4 import { addComment, openIssue, setIssueState } from "../src/actions/issues.ts";
4 import { addComment, markQuestion, openIssue, setIssueState } from "../src/actions/issues.ts";
55 import { openPull } from "../src/actions/pulls.ts";
66 import { commitToBranch } from "../src/actions/repos.ts";
77
8 import { commentAnchor, getIssue, listComments } from "../src/core/issues.ts";
8 import { commentAnchor, getIssue, listComments, parseQuestion } from "../src/core/issues.ts";
99 import { foldJs } from "../src/web/fold.ts";
1010 import { shellJs } from "../src/web/client.ts";
1111 import { css } from "../src/web/style.ts";
@@ -136,6 +136,55 @@ test("a pull thread windows too, and the link keeps the page's other query", asy
136136 expect(all.match(/class="tl-item" id="c-/g)?.length).toBe(70);
137137 });
138138
139 test("an open question stays out of the fold on an issue; a settled one folds", async () => {
140 const repo = f.repos[0]!;
141 const opened = openIssue(f.app, f.owner, repo, { title: "Asked", body: "asked" });
142 if (!opened.ok) throw new Error(String(opened.error));
143 const thread = opened.value;
144 const said: string[] = [];
145 for (let i = 0; i < 70; i++) {
146 const added = addComment(f.app, f.owner, repo, thread, i === 3 ? "which database?" : `plain ${i}`);
147 if (!added.ok) throw new Error(String(added.error));
148 said.push(added.value.id);
149 }
150 const url = `${f.base}/${repo.ownerName}/${repo.name}/issues/${thread.number}`;
151 const read = async (): Promise<string> => (await fetch(url, { headers: { cookie: f.ownerCookie } })).text();
152 const question = said[3]!;
153 expect(await read()).not.toContain("which database?");
154
155 // Marked from the page's own form: same origin, a session cookie.
156 const post = await fetch(`${url}/comments/${question}/question`, {
157 method: "POST",
158 redirect: "manual",
159 headers: { cookie: f.ownerCookie, origin: f.base, "content-type": "application/x-www-form-urlencoded" },
160 body: "state=open",
161 });
162 expect(post.status).toBe(303);
163 const asked = await read();
164 expect(asked).toContain("which database?");
165 expect(asked).toContain("Question, open");
166 expect(asked).toContain("Show 19 earlier items");
167 expect(listComments(f.app.db, thread.id, { kind: "comment" })[3]!.question).toBe("open");
168
169 const settled = markQuestion(f.app, f.owner, repo, thread, question, "settled");
170 expect(settled.ok).toBe(true);
171 const after = await read();
172 expect(after).not.toContain("which database?");
173 expect(after).toContain("Show 20 earlier items");
174 });
175
176 test("only the comment's author or a writer may change a question, and a bad state is refused", async () => {
177 const repo = f.repos[0]!;
178 const opened = openIssue(f.app, f.owner, repo, { title: "Who", body: "who" });
179 if (!opened.ok) throw new Error(String(opened.error));
180 const added = addComment(f.app, f.owner, repo, opened.value, "is this ok?");
181 if (!added.ok) throw new Error(String(added.error));
182 expect(markQuestion(f.app, undefined, repo, opened.value, added.value.id, "open").ok).toBe(false);
183 expect(markQuestion(f.app, f.owner, repo, opened.value, "nope", "open").ok).toBe(false);
184 expect(parseQuestion("later")).toBeUndefined();
185 expect(parseQuestion("none")).toBeNull();
186 });
187
139188 test("everything before the newest comment folds with its counts; the newest stays out of the fold", async () => {
140189 const html = await get();
141190 const fold = html.match(/<details class="tl-fold" id="history">([\s\S]*?)<\/details>/);
@@ -205,7 +254,7 @@ test("an entry still waiting for its answer stays out of the fold, and splits it
205254 made.push(at);
206255 }
207256 expect(new Set(made).size).toBe(6);
208 const ctx = { app: f.app, url: new URL(`${f.base}${path}`) } as unknown as Ctx;
257 const ctx = { app: f.app, auth: {}, url: new URL(`${f.base}${path}`) } as unknown as Ctx;
209258 const ask = (open: boolean): Entry => ({
210259 at: made[2]!,
211260 node: html`<div class="tl-item" data-kind="event">STANDING REQUEST</div>`,
@@ -237,3 +286,30 @@ test("a request for changes stands while it is its reviewer's newest verdict on
237286 expect(open(true)).toEqual(["1"]);
238287 expect(open(false)).toEqual([]);
239288 });
289
290 test("an ordinary comment carries no question form; the composer offers 'Ask as a question', and posting with it marks the comment", async () => {
291 const repo = f.repos[0]!;
292 const opened = openIssue(f.app, f.owner, repo, { title: "Composer", body: "c" });
293 if (!opened.ok) throw new Error(String(opened.error));
294 const addr = `${f.base}/${repo.ownerName}/${repo.name}/issues/${opened.value.number}`;
295 const added = addComment(f.app, f.owner, repo, opened.value, "just a comment");
296 if (!added.ok) throw new Error(String(added.error));
297 const read = async (): Promise<string> => (await fetch(addr, { headers: { cookie: f.ownerCookie } })).text();
298 const page = await read();
299 expect(page).not.toContain("/question");
300 expect(page).toContain('name="question" value="open"');
301
302 const post = await fetch(`${addr}/comments`, {
303 method: "POST",
304 redirect: "manual",
305 headers: { cookie: f.ownerCookie, origin: f.base, "content-type": "application/x-www-form-urlencoded" },
306 body: "body=which+one%3F&question=open",
307 });
308 expect(post.status).toBe(303);
309 const asked = listComments(f.app.db, opened.value.id, { kind: "comment" }).find((c) => c.body === "which one?");
310 expect(asked?.question).toBe("open");
311 const after = await read();
312 expect(after).toContain("Question, open");
313 expect(after).toContain(`/comments/${asked!.id}/question`);
314 expect(after.match(/\/question"/g)?.length).toBe(1);
315 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs